【问题标题】:rails activerecord: how to specify the inverse relationship to "belongs_to ... :class_name ..."rails activerecord:如何指定与“belongs_to ...:class_name ...”的反向关系
【发布时间】:2013-01-19 01:27:00
【问题描述】:

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

并且该关联在 Contact -> 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 关联的倒数的方法?

【问题讨论】:

标签: ruby-on-rails rails-activerecord


【解决方案1】:

类似以下的方法会起作用:

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

【讨论】:

  • 非常有帮助(有一次更正)-foreign_key 是我所缺少的。至于contacts() 方法,至少对于rails 3.0.19,我认为merge 需要Hash 并且关联是类Array,所以email_contacts + phone_contacts 是有效的。如果您同意更正是适当的并且您将对其进行编辑,我会将其标记为已接受。再次感谢您的出色回答。
  • 关联是类 ActiveRecord::Relation(不是 Array),但是 + 很可能是正确的,而不是合并 >_>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多