0

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.

1 Answers1

0

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
Camway
  • 1,010
  • 14
  • 23