Last Updated: April 21, 2017
·
1.237K
· pzgz

Trick to use form for updating rails-settings bounding to the model

Sometime, we do have settings bound to model, and we might need to use form to updating the settings as we updating regular attributes. Following is the trick.

First, we can put following codes into a .rb file at somewhere inside lib directory.

class ActiveRecord::Base
  def self.has_settings_on(*args)
    include RailsSettings::Extend
    args.each do |setting_name|
      attr_accessible setting_name
      define_method(setting_name)       { self.settings.send(setting_name) }
      define_method("#{setting_name}=") { |value| self.settings.send("#{setting_name}=", value) }
    end
  end
end

Then, we need to load this rb file by put a require in somewhere inside /config/initializers.

After that, in the models with settings bound. We can simply use method has_settings_on to specified settings. This method will declare the settings, as well set them in attr_accessible list.

Be aware I am using rails-settings-cached. If you are using other version, make sure change the codes to fit in.

1 Response
Add your response

By any chance do you an example that is a little more detailed? I'm not as experienced as you are and I'm struggling with this exact situation when Im trying to have a User form to update several attributes.

over 1 year ago ·