huacnlee / rails-settings-cached

Global settings for your Rails application.
Other
1.06k stars 202 forks source link

Setting.foo is different than Setting.find_by_var('foo').value #122

Closed brentkearney closed 7 years ago

brentkearney commented 7 years ago

I sometimes find that Setting.foo returns a value that is different from Setting.find_by(var: 'foo').value. I'm not sure how/when this happens. In my Settings model, I'm removing some keys and values and adding others, then saving with Setting.merge!(section, new_location).

huacnlee commented 7 years ago

Because rails-settings-cache wants keep the origianl value type, so that store value with YAML.dump, and then when you calling Setting.foo, return the value of YAML.load.

But the Setting.find_by(var: 'foo') way is ActiveRecord way.

brentkearney commented 7 years ago

Your example here: https://github.com/huacnlee/rails-settings-cached#how-to-create-a-list-form-to-manage-settings uses this method.

def get_setting
  @setting = Setting.find_by(var: params[:id]) || Setting.new(var: params[:id])
end

def update
  if @setting.value != params[:setting][:value]
    @setting.value = params[:setting][:value]
    @setting.save
    ...

But then, the @setting object will be a different object, will have a different @setting.value value than what will be returned from Setting.send(params[:id]). At least, I get different values when I save this way.

brentkearney commented 7 years ago

What if I don't know the name of the setting? How can I go through them all and modify them? For example:

Setting.get_all.keys.each do |var_name|
    s = Setting.find_by_var(var_name)
    s.value = new_value
    s.save
end

There appears to be no way to save a setting with this format: Setting.var_name = new_value, when "var_name" is a variable. Or is there a way to do that?