我正在使用 Rails 4 并想定义动态属性,例如:
(0..6).each do |i|
attr_accessible "attr-#{i}"
现在它失败了
NoMethodError: undefined method `attr_accessible' for #<Class:0x007fdeb8911380>
我相信这是因为 attr_accessible 在 Rails 4 中不再使用,那么我该如何实现呢?谢谢。
我正在使用 Rails 4 并想定义动态属性,例如:
(0..6).each do |i|
attr_accessible "attr-#{i}"
现在它失败了
NoMethodError: undefined method `attr_accessible' for #<Class:0x007fdeb8911380>
我相信这是因为 attr_accessible 在 Rails 4 中不再使用,那么我该如何实现呢?谢谢。
尝试这个:
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