How do you override the getter method for a Rails has_one association?

限于喜欢 提交于 2019-12-04 05:40:21
Michael Johnston

As of Rails 3, alias_method is not the preferred way to override association methods. Quoting from the docs:

Overriding generated methods

Association methods are generated in a module that is included into the model class, which allows you to easily override with your own methods and call the original generated method with super. For example:

class Car < ActiveRecord::Base
  belongs_to :owner
  belongs_to :old_owner
  def owner=(new_owner)
    self.old_owner = self.owner
    super
  end
end

If your model class is Project, the module is named Project::GeneratedFeatureMethods. The GeneratedFeatureMethods module is included in the model class immediately after the (anonymous) generated attributes methods module, meaning an association will override the methods for an attribute with the same name.

You can alias the original method, then define a new one with the same name.

For example:

class MyModel < ActiveRecord::Base
  has_one :associated_model

  alias :old_associated_model :associated_model

  def associated_model
    old_associated_model || AssociatedModel.new(my_model_id: id)
  end

end

I don't know if this is the canonical way to handle this situation, but it should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!