如何覆盖Rails has_one关联的getter方法? [英] How do you override the getter method for a Rails has_one association?

查看:83
本文介绍了如何覆盖Rails has_one关联的getter方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重写/扩展Rails has_one关联方法,以便它始终返回关联类的实例. (如果数据库中不存在该数据库,我想创建一个新数据库并将其分配给父实例.)

I want to override/extend a Rails has_one association method so that it always returns an instance of the associated class. (If none already exists in the database, I want to create a new one and assign it to the parent instance.)

理想情况下,我想通过内置的Rails关联扩展机制来执行此操作.但是,我不知道"getter"方法的名称,因此也不知道要覆盖的内容.

Ideally, I'd like to do this through the built-in Rails association extension mechanism. However, I don't know the name of the "getter" method, and so I don't know what to override.

如何覆盖关联获取器,以便在零时实例化新对象?

How do I override the association getter so that I can instantiate a new object when it's nil?

推荐答案

从Rails 3开始,alias_method不是重写关联方法的首选方法.引用

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

覆盖生成的方法

关联方法是在模型类中包含的模块中生成的,使用该模块,您可以轻松地使用自己的方法进行覆盖,并使用super调用原始生成的方法.例如:

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

如果您的模型类是Project,则该模块名为Project :: GeneratedFeatureMethods.在(匿名)生成的属性方法模块之后,模型类中立即包含了GeneratedFeatureMethods模块,这意味着关联将覆盖具有相同名称的属性的方法.

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.

这篇关于如何覆盖Rails has_one关联的getter方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆