MikeC
MikeC

Reputation: 480

has_many :through and has_many relationship between same 2 models

A list has one owner (a user). A list also has a number of panelists (also users). I have tried defining the relationships between the three models: User, List, and Panelist. But I'm getting nowhere.

user.rb

class User < ActiveRecord::Base
  has_many :lists
  has_many :panelMemberships, :through => :panelists, :source => :lists
end

list.rb

class List < ActiveRecord::Base
  belongs_to :user
  has_many :panelMembers, :through => :panelists, :source => :user
end

panelist.rb

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

I've tried all different combinations but nothing seems to work. Thanks in advance for any help you can provide.

Upvotes: 0

Views: 187

Answers (1)

ussferox
ussferox

Reputation: 490

The model also has to have a has_many relationship for whatever the through model is, so wherever you have has_many :x, through: :y, you also need to say has_many :y. You also shouldn't have a panelist model separate from your user model if panelists are users (unless you're doing STI, which you're not). From what I understand, you're trying to do something like this:

class User < ActiveRecord::Base
  has_many :owned_lists, class_name: "List", foreign_key: :owner_id  # this is for the owner/list relationship
  has_and_belongs_to_many :lists  # for the normal panelist / list relationship
end

class List < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_and_belongs_to_many :users
end

Then you'll need to make a migration for a users_lists (with user id and list id) table which will be your join table but won't need its own model. But if you really want to keep the through relationship (good for if you do other stuff with the join model), then you'd do:

class User < ActiveRecord::Base
  has_many :owned_lists, class_name: "List", foreign_key: :owner_id  # this is for the owner/list relationship
  has_many :panel_memberships
  has_many :lists, through: :panel_memberships 
end

class List < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_many :panel_memberships
  has_many :users, through: :panel_memberships
end

class PanelMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :list

Upvotes: 1

Related Questions