我有belongs_to ... :class_name
关联工作正常,但无法看到如何创建相互关联。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
人和协会在联系工作正常 - >关系网方向(通过名称:电话:电子邮件)
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
当然,我可以byp S上的关联,并直接进行查找:
Contacts.where("(email_id = ?) OR (phone_id = ?)", r.id. r.id)
但我相信有一些(更好)的方式,例如,指定belongs_to ... :class_name
协会的倒数的方式吗?
关于AR协会非常有帮助的网站是http://guides.rubyonrails.org/association_basics.html – user934801
感谢我refered访问该文档了很多时间,它不afaik地址的相对'belongs_to ... class_name' – jpwynn