Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a form for the rails-settings plugin

I have a Rails 3 App that has needs some user defined settings. I would like to use this https://github.com/ledermann/rails-settings plugin. I have it working in the rails console. But I am having trouble getting working in a form. Do I use fields_for & attr_accessible? If so I am having no luck.

I need to add settings for two Models:

For example, settings that are specific to a User,

user = User.find(123)
user.settings.color = :red
user.settings.color
# => :red

user.settings.all
# => { "color" => :red }

(The above works fine for me in the console.)

but I need to administer them through a standard web form. I'd love to know how others are handling this.

Thanks.

like image 890
Beau Avatar asked Sep 15 '11 04:09

Beau


1 Answers

What I did is add dynamic setters/getters to my User class as such

class User < ActiveRecord::Base

  has_settings

  def self.settings_attr_accessor(*args)
    args.each do |method_name|
      eval "
        def #{method_name}
          self.settings.send(:#{method_name})
        end
        def #{method_name}=(value)
          self.settings.send(:#{method_name}=, value)
        end
      "
    end
  end

  settings_attr_accessor :color, :currency, :time_zone

end

With that, you can use "color" just like any other attribute of your User model. Also it's very simple to add more settings, just add them to the list

like image 181
Arnaud Avatar answered Sep 21 '22 19:09

Arnaud