来自 Rails4 InstanceMethods 的设置器用于不存在的字段
Setters from Rails4 InstanceMethods for non-existing fields
我正在写一个 gem rails4,我可以在其中添加动态属性,这些属性不会在实际模型中持续存在 table,而是会保存在我的第二个 table 中并带有参考。
现在我有 before_validation 实例方法,我试图将默认值设置为动态添加的属性。
我收到错误
can't write unknown attribute
密码是
self[attr_name.to_sym]=attr_type[:default_value]
请就此提出建议,如何从不存在的字段的实例方法中执行设置器。
我在 ClassMethods 中使用了 instance_variable_set。
您可以在模型中为此目的使用 attr_accessor
方法。
class Sample << ActiveRecord::Base
attr_accessor :attr_name
#setter method
def attr_name=(val)
self[:attr_name] = val
end
#getter method
def attr_name
self[:attr_name]
end
end
现在,您可以像下面这样调用任何实例方法。
self[attr_name.to_sym]=attr_type[:default_value]
我正在写一个 gem rails4,我可以在其中添加动态属性,这些属性不会在实际模型中持续存在 table,而是会保存在我的第二个 table 中并带有参考。
现在我有 before_validation 实例方法,我试图将默认值设置为动态添加的属性。 我收到错误
can't write unknown attribute
密码是
self[attr_name.to_sym]=attr_type[:default_value]
请就此提出建议,如何从不存在的字段的实例方法中执行设置器。
我在 ClassMethods 中使用了 instance_variable_set。
您可以在模型中为此目的使用 attr_accessor
方法。
class Sample << ActiveRecord::Base
attr_accessor :attr_name
#setter method
def attr_name=(val)
self[:attr_name] = val
end
#getter method
def attr_name
self[:attr_name]
end
end
现在,您可以像下面这样调用任何实例方法。
self[attr_name.to_sym]=attr_type[:default_value]