slate-studio / activeadmin-settings

Settings backend for activeadmin based projects - pretty handy tool.
88 stars 65 forks source link

Many request to database #29

Closed yurgon closed 10 years ago

yurgon commented 10 years ago

Hi, if I have 5 custom block in my app with activeadmin-settings Page generate 5 request to database(( Can I do one request to get 5 setting field ?

rlupiichuk commented 10 years ago

Hi, Yurgon

I'll try to help you although I haven't been using activeadmin-settings for a long time by myself.

This is the implementation of settings_value helper:

    def settings_value(name, locale = nil)
      Setting.value(name, locale)
    end

This is how settings is actually fetched in Mongoid:

    def self.value(name, locale)
      find_or_create_by(:name => name, :locale => (locale || I18n.locale)).value
    end

So basically you can do this somewhere in your controller (for ActiveRecord it will be a bit different):

settings = ActiveadminSettings::Setting.or(
  {:name => "Setting 1", :locale => I18n.locale},
  {:name => "Setting 2", :locale => I18n.locale},
  {:name => "Setting 3", :locale => I18n.locale})
if settings.size == 3
  settings_hash = settings.map{|s| [s.name, s.value]}.to_h
  @setting1 = settings_hash["Setting 1"]
  @setting2 = settings_hash["Setting 2"]
  @setting3 = settings_hash["Setting 3"]
else
  # this is the first time we are fetching these settings, lets create them
  @setting1 = settings_value("Setting 1")
  @setting2 = settings_value("Setting 2")
  @setting3 = settings_value("Setting 3")
end

You can create your own helper based on this idea. Or you can even extend activeadmin-settings and make PR for this. Good luck!

yurgon commented 10 years ago

Thx, men For ActiveRecord how I do this?

rlupiichuk commented 10 years ago

Something like

settings = ActiveadminSettings::Setting.where("name in (?) and locale=?", ["Setting 1", "Setting 2", "Setting 3"], I18n.locale)

The rest will be the same.

yurgon commented 10 years ago

Yea, I just did so Thx a lot ))

yurgon commented 10 years ago

Okey, I did pretty simple

@settings = Hash[ActiveadminSettings::Setting.all.map{|s| [s.name, s.value]}] and to use @settings['Block 1']