アソシエーションは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
そして、関連付けは連絡先-> 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
関連の逆数を指定する方法?