我的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
关联倒数的方法?