可以在 Rails 中给关联关联别名吗? [英] Possible to alias a belongs_to association in Rails?

查看:30
本文介绍了可以在 Rails 中给关联关联别名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 belongs_to 关联的模型:

I have a model with a belongs_to association:

class Car < ActiveRecord::Base
  belongs_to :vendor
end

所以我可以调用car.vendor.但我也想调用car.company!所以,我有以下几点:

So I can call car.vendor. But I also want to call car.company! So, I have the following:

class Car < ActiveRecord::Base
  belongs_to :vendor
  def company
    vendor
  end
end

但这并不能解决分配情况car.company = 'ford',所以我需要为此创建另一种方法.是否有一个简单的 alias 机制可以用于关联?我可以只使用 alias_method :company, :vendoralias_method :company=, :vendor= 吗?

but that doesn't solve the assignment situation car.company = 'ford', so I need to create another method for that. Is there a simple alias mechanism I can use for associations? Can I just use alias_method :company, :vendor and alias_method :company=, :vendor=?

推荐答案

不,它不会寻找 company_id 例如改变你的代码如下

No it doesn't look for company_id for instance change your code as follows

class Car < ActiveRecord::Base
   belongs_to :vendor
   belongs_to :company, :class_name => :Vendor,:foreign_key => "vendor_id"
end

在 Rails4 中

我们可以使用别名属性.

In Rails4

We can use alias attribute.

alias_attribute :company, :vendor

这篇关于可以在 Rails 中给关联关联别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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