Rails:has_many通过另一个表与self联系

时间:2015-09-02 10:46:13

标签: ruby-on-rails ruby-on-rails-4

我有一个users表和一个contacts表。这些是contacts表的架构:

CREATE TABLE "contacts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id" integer, "contact_id" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "users_id" integer);
CREATE INDEX "index_contacts_on_user_id" ON "contacts" ("user_id");
CREATE INDEX "index_contacts_on_contact_id" ON "contacts" ("contact_id");
CREATE INDEX "index_contacts_on_users_id" ON "contacts" ("users_id");

因此,基本上用户可以拥有多个联系人,在contact_id表格中标明。

我定义了这样的关联:

class Contact < ActiveRecord::Base
    belongs_to :user
    has_many :users, foreign_key: :contact_id
end

class User < ActiveRecord::Base
    has_many :users, through: :contacts
end

现在问题:当尝试检索用户的联系人调用相应的方法@user.users时,我收到以下错误:

  

无法找到关联:模型用户中的联系人

这甚至意味着什么?为什么我会收到此错误?

我想帮助我们解决这个问题。另外,有没有办法可以重命名关联,而不是调用@user.users我会调用@user.contacts,这会更有意义?

3 个答案:

答案 0 :(得分:1)

通讯录表

create_table :contacts do |t|
  t.integer :user_id
  t.integer :related_id
end

使用has_and_belongs_to_many

class Word < ActiveRecord::Base 
  has_and_belongs_to_many :users, class_name: 'User',
   join_table: 'contacts', association_foreign_key: 'related_id'
end

使用has_many至:

class Contact < ActiveRecord::Base
  belongs_to :user, foreign_key: :related_id
  has_many :users, foreign_key: :user_id
end

class User < ActiveRecord::Base
  has_many :users, through: :contacts
end

答案 1 :(得分:1)

has_many :through与三个模型一起使用,而不是两个:

  

此关联表示通过第三个​​模型,可以将声明模型与另一个模型的零个或多个实例匹配。

示例代码继续解释这可以用于协调医生,约会和患者。

:through属性需要作为其自己的关联提供:

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

这就是您收到错误的原因:has_many :users, through: :contacts需要contacts上的另一个关联User(您没有)。

对于您的问题,has_many :contacts可能就足够了。

答案 2 :(得分:0)

终于把它弄清楚了。

解决方案:

class User < ActiveRecord::Base
    has_and_belongs_to_many :contacts, join_table: :contacts, class_name: 'User',
        foreign_key: :user_id, association_foreign_key: :contact_id
end