两个模型之间有多个has_many关系

时间:2014-01-05 02:51:37

标签: ruby-on-rails ruby-on-rails-3 activerecord

用户可以通过三种方式连接到列表:他可以拥有它(即他创建了它),他可以是小组成员(他定期投票),或者他可以喜欢它。我已经处理了前两种情况,但无法让第三种情况(“收藏”)起作用。所有权由List模型上的外键“所有者”的has_many关系处理。小组成员通过与联接表lists_users的has_and_belongs_to_many关系来处理。我正试图通过has_many来做收藏:通过但它不起作用:

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

如果一切顺利,我希望能够做user.favorite_lists并获得包含一个或多个列表的关联。现在,我得到“ActiveRecord :: HasManyThroughSourceAssociationNotFoundError:找不到源关联:favorite_list或:Favorite_lists in model Favorite。尝试'has_many:favorite_lists,:through =&gt;:favorites,:source =&gt; “

非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

您需要指定has_many :through的来源:

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

我不确定,但我认为此处不需要:class_name