Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails activerecord:如何指定与";属于类别“名称…”;_Ruby On Rails_Rails Activerecord - Fatal编程技术网

Ruby on rails rails activerecord:如何指定与";属于类别“名称…”;

Ruby on rails rails activerecord:如何指定与";属于类别“名称…”;,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我的属于…: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 work

我的
属于…: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条目的所有联系人,我无法使用:

r = Rolodex.first
r.contacts
# column contacts.rolodex_id does not exist
当然,我可以绕过关联直接进行查找:

Contacts.where("(email_id = ?) OR (phone_id = ?)", r.id. r.id)

但是我假设有某种(更好的)方法,例如,一种指定
所属函数的倒数的方法:类名
关联?

类似于以下内容的内容将起作用:

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
classrolodex
关于AR关联的一个非常有用的网站是,感谢我多次参考该文档,但它没有提到“属于”\u。。。class_name'非常有用(有一处更正)-外键是我缺少的。至于contacts()方法,至少对于rails 3.0.19,我认为merge需要散列和关联是类数组,所以email\u contacts+phone\u contacts才有效。如果您同意更正是适当的,并且您将对其进行编辑,我会将其标记为接受。再次感谢您的回答。关联是类ActiveRecord::Relation(不是数组),但是+很可能是正确的,而不是merge>\u>
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