【发布时间】:2013-01-19 01:27:00
【问题描述】:
我的 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 方向上运行良好(通过名称 :phone 和 :email)
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 关联的倒数的方法?
【问题讨论】:
-
一个非常有用的关于 AR 关联的网站是 guides.rubyonrails.org/association_basics.html
-
感谢我多次参考该文档,但它并没有解决“belongs_to ... class_name”的倒数问题
标签: ruby-on-rails rails-activerecord