2016-03-28 58 views
0

我用Rails 4要定义动态属性,是这样的:attr_accessible为Rails 4动态属性

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

现在它failling说

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

我相信这是因为attr_accessible在Rails 4中不再使用,那么我如何实现这一点? 谢谢。

回答

0

试试这个:

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 
+0

正是一直在寻找!谢谢你的时间。 – WhomWhomWhom