MikeC
MikeC

Reputation: 480

Multiple has_many relationships between two models

A user can be connected to a list in three ways: he can own it (i.e. he created it), he can be a panelist (he votes on it periodically), or he can favorite it. I've taken care of the first two cases but can't get the third one ("favorites") to work. The ownership is taken care of by a has_many relationship with the foreign key "owner" on the List model. The panelist is taken care of by a has_and_belongs_to_many relationship with the join table lists_users. I'm trying to do favorites via has_many :through but it's not working:

user.rb:

has_many :owned_lists, :class_name => "List", :foreign_key=> :owner  # this is for the owner/list relationship
has_and_belongs_to_many :lists  # for the normal panelist / list relationship
has_many :favorites
has_many :favorite_lists, :through=> :favorites, :class_name => "List"

list.rb:

  belongs_to :owner, :class_name=> "User", :foreign_key => :owner
  has_many :favoriters, :through=> :favorites, :class_name => "User"
  has_and_belongs_to_many :users

favorite.rb

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

If all goes well, I'd like to be able to do user.favorite_lists and get an association containing one or more lists. Right now, I'm getting "ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :favorite_list or :favorite_lists in model Favorite. Try 'has_many :favorite_lists, :through => :favorites, :source => '

Any help you can provide would be much appreciated.

Upvotes: 0

Views: 305

Answers (1)

BroiSatse
BroiSatse

Reputation: 44725

You need to specify source for has_many :through:

has_many :favorites
has_many :favorite_lists, :through=> :favorites, :class_name => "List", :source => :list

I am not sure, but I think :class_name is not necessary here

Upvotes: 0

Related Questions