ruby-on-rails-4dynamic-attributes

attr_accessible for Rails 4 dynamic attributes


I'm using Rails 4 and want to define dynamic attributes, something like:

(0..6).each do |i|
    attr_accessible "attr-#{i}"

right now it's failling saying

NoMethodError: undefined method `attr_accessible' for #<Class:0x007fdeb8911380>

I believe this is because attr_accessible is no longer use in Rails 4, so how could i achieve this? Thanks.


Solution

  • Try this:

    dynamic_attributes = {test: 1, test2: 2, test3: 3}
    #object could be self depending on the context
    object.instance_eval(class << self; self; end) }.class_eval do
      dynamic_attributes.each do |attr, value|
        define_method(attr){ value }
        define_method(attr){|new_value| dynamic_attributes[attr] = new_value }
      end
    end