0

我的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

并且该关联在 Contact -> 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关联倒数的方法?

4

1 回答 1

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
于 2013-01-19T02:40:11.373 回答