加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在mixin /模块中覆盖模型的属性访问器

发布时间:2020-12-17 03:38:18 所属栏目:百科 来源:网络整理
导读:我有一个包含模块的模型.我想在模块中覆盖模型的访问器方法. 例如: class Blah ActiveRecord::Base include GnarlyFeatures # database field: nameendmodule GnarlyFeatures def name=(value) write_attribute :name,"Your New Name" endend 这显然不起作
我有一个包含模块的模型.我想在模块中覆盖模型的访问器方法.

例如:

class Blah < ActiveRecord::Base
  include GnarlyFeatures
  # database field: name
end

module GnarlyFeatures
  def name=(value)
    write_attribute :name,"Your New Name"
  end
end

这显然不起作用.有什么想法来完成这个?

解决方法

您的代码看起来正确.我们正在使用这个确切的模式没有任何麻烦.

如果我没记错,Rails会使用#method_missing作为属性设置器,因此您的模块将优先,阻止ActiveRecord的setter.

如果您使用的是ActiveSupport :: Concern(请参阅this blog post,那么您的实例方法需要进入特殊模块:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读