【问题标题】:Multiple has_many relationships between two models两个模型之间的多个 has_many 关系
【发布时间】:2014-01-05 10:59:49
【问题描述】:

用户可以通过三种方式连接到列表:他可以拥有它(即他创建了它),他可以成为小组成员(他定期投票),或者他可以收藏它。我已经处理了前两个案例,但无法让第三个(“收藏夹”)工作。所有权由与 List 模型上的外键“所有者”的 has_many 关系处理。小组成员由与连接表 lists_users 的 has_and_belongs_to_many 关系处理。我正在尝试通过 has_many :through 进行收藏,但它不起作用:

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

最喜欢的.rb

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

如果一切顺利,我希望能够执行 user.favorite_lists 并获得包含一个或多个列表的关联。现在,我收到“ActiveRecord::HasManyThroughSourceAssociationNotFoundError:在模型收藏夹中找不到源关联:favorite_list 或 :favorite_lists。尝试 'has_many :favorite_lists, :through => :favorites, :source => '

您能提供的任何帮助将不胜感激。

【问题讨论】:

  • 您能描述一下这里的“不工作”是什么意思吗?
  • 我知道它不能回答您的问题,但是 rolify gem 是针对这种情况的一个很好的打包解决方案。 github.com/EppO/rolify

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


【解决方案1】:

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

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

我不确定,但我认为这里不需要:class_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多