rails activerecord:如何指定与“belongs_to ...:class_name ...”的反向关系

时间:2013-01-19 01:27:01

标签: ruby-on-rails rails-activerecord

我的belongs_to ... :class_name关联工作正常,但无法看到如何创建互惠关联。

这就是我现在所拥有的:

class Contact < ActiveRecord::Base
  # has fields email_id and phone_id
  belongs_to :email, :class_name => 'Rolodex' # this works fine
  belongs_to :phone, :class_name => 'Rolodex' # this works fine
end

class Rolodex < ActiveRecord::Base
  # entry:string  holds a phone#, email address, etc
  has_many :contacts    # does NOT WORK, since no Contact.rolodex_id field
end

该协会在联系方式中运作良好 - &gt; Rolodex方向(通过名称:电话和:电子邮件)

john = Contact.first
john.phone.entry
# correctly returns the person's rolodex.entry for their phone, if any
john.email.entry
# correctly returns the person's rolodex.entry for their email, if any

但是,如果我想查找共享rolodex条目的所有联系人,我将无法使用:

r = Rolodex.first
r.contacts
# column contacts.rolodex_id does not exist

当然,我可以绕过关联并直接进行查找:

Contacts.where("(email_id = ?) OR (phone_id = ?)", r.id. r.id)

但我认为有一些(更好的)方式,例如,指定belongs_to ... :class_name关联的倒数的方法?

1 个答案:

答案 0 :(得分:2)

以下内容可行:

class Rolodex < ActiveRecord::Base
  has_many :email_contacts, class_name: 'Contact', foreign_key: 'email_id'
  has_many :phone_contacts, class_name: 'Contact', foreign_key: 'phone_id'

  def contacts
    email_contacts + phone_contacts
  end
end