Eki Eqbal
Eki Eqbal

Reputation: 6057

How to create has_many and belong_to one associations in Rails using a join table?

I have the following models:List that has (name and user_id fields) and User.

Each list has many users. And each list belong to ONE user.

I created client_lists table:

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

Now for the first relationship it's easy to say that a list belong to a user and that a user has many lists:

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

And

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

Anyways, how am I supposed to find the list of clients through client_lists table?

I added HABTM relationship for List

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

Then tried List.first.clients and got the following error:

NameError: uninitialized constant List::Client

Upvotes: 0

Views: 36

Answers (1)

Eki Eqbal
Eki Eqbal

Reputation: 6057

I had to create ClientLists model:

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

Then adding the following to List model:

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

Upvotes: 1

Related Questions