【问题标题】:How to create has_many and belong_to one associations in Rails using a join table?如何使用连接表在 Rails 中创建 has_many 和 belongs_to 一个关联?
【发布时间】:2015-01-13 15:55:05
【问题描述】:

我有以下模型:List 具有(名称和用户 ID 字段)和 User

每个列表都有很多用户。每个列表都属于一个用户。

我创建了client_lists 表:

class CreateClientListsTable < ActiveRecord::Migration
  def change
    create_table :client_lists do |t|
      t.integer :user_id
      t.integer :list_id
    end
    add_index :client_lists, :user_id
    add_index :client_lists, :list_id
  end
end

现在对于第一个关系,很容易说一个列表属于一个用户,并且一个用户有很多列表:

class List < ActiveRecord::Base
  belongs_to :user
  validates  :user, :presence => true
end

还有

class User < ActiveRecord::Base
  has_many :lists, :dependent => :destroy
end

无论如何,我应该如何通过 client_lists 表找到客户列表?

我为 List 添加了 HABTM 关系

class List < ActiveRecord::Base
  has_and_belongs_to_many :clients, :join_table => "client_lists", :foreign_key => "user_id"
end

然后尝试List.first.clients,得到如下错误:

NameError: uninitialized constant List::Client

【问题讨论】:

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


    【解决方案1】:

    我必须创建ClientLists 模型:

    class ClientLists < ActiveRecord::Base
      belongs_to :user
      belongs_to :list
    end
    

    然后将以下内容添加到 List 模型中:

      has_many :client_lists, :class_name => "ClientLists", :foreign_key => "list_id"
      has_many :clients, through: :client_lists, source: :user
    

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 2015-09-11
      相关资源
      最近更新 更多