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