Ken*_*llB 5 ruby ruby-on-rails
我有一个包含模块的模型.我想在模块中覆盖模型的访问器方法.
例如:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
def name=(value)
write_attribute :name, "Your New Name"
end
end
Run Code Online (Sandbox Code Playgroud)
这显然不起作用.有什么想法来完成这个?
您的代码看起来正确.我们正在使用这个确切的模式没有任何麻烦.
如果我没记错,Rails会将#method_missing用于属性设置器,因此您的模块将优先,阻止ActiveRecord的setter.
如果您正在使用ActiveSupport :: Concern(请参阅此博客文章,那么您的实例方法需要进入特殊模块:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
extend ActiveSupport::Concern
included do
def name=(value)
write_attribute :name, value
end
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2431 次 |
| 最近记录: |