0

アソシエーションは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関連の逆数を指定する方法?

4

1 に答える 1

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
于 2013-01-19T02:40:11.373 に答える