2013-01-19 58 views
0

我有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协会的倒数的方式吗?

+0

关于AR协会非常有帮助的网站是http://guides.rubyonrails.org/association_basics.html – user934801

+0

感谢我refered访问该文档了很多时间,它不afaik地址的相对'belongs_to ... class_name' – jpwynn

回答

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 
+0

非常有帮助(有一个更正) - foreign_key是我失踪。至于contacts()方法,至少对于rails 3.0.19,我认为合并期望哈希和关联是类Array,所以email_contacts + phone_contacts是有效的。如果您同意更正是合适的,您将对其进行编辑,我会将其标记为已接受。再次感谢您的出色答案。 – jpwynn

+0

该关联是类ActiveRecord :: Relation(不是Array),但+很可能是正确的,而不是合并> _> – sevenseacat