我有三个模型:user,guideline和favourite_guideline(目的是让用户可以创建自己喜欢的指南列表)。
尝试添加收藏夹
时出现关联错误ActiveRecord :: HasManyThroughSourceAssociationNotFoundError in GuidelinesController#最爱 无法找到源关联:收藏夹或:收藏夹 模特FavouriteGuideline。试试'has_many:favorites,:through => :favourite_guidelines,:source => ”。它是以下之一:指南还是 :用户
class User < ActiveRecord::Base
has_many :guidelines
has_many :favourite_guidelines
has_many :favourites, through: :favourite_guidelines
end
class Guideline < ActiveRecord::Base
belongs_to :user
has_many :favourite_recipes
has_many :favourited_by, through: :favourite_recipes, source: :user
end
class FavouriteGuideline < ActiveRecord::Base
belongs_to :guideline
belongs_to :user
end
指南控制器中的我最喜欢的动作是:
def favourite
type = params[:type]
if type == "favourite"
current_user.favourites << @guideline
redirect_to :back, notice: 'You favourited #{@guideline.name}'
elsif type == "unfavourite"
current_user.favourites.delete(@guideline)
redirect_to :back, notice: 'Unfavourited #{@guideline.name}'
else
# Type missing, nothing happens
redirect_to :back, notice: 'Nothing happened.'
end
end
答案 0 :(得分:4)
好的,
尝试'has_many:favorites,:through =&gt; :favourite_guidelines,:source =&gt; ”。它是以下之一:指南还是:用户?
它是:指南。
has_many :favourites, through: :favourite_guidelines, source: :guideline
:源 指定has_many:through查询使用的源关联名称。只有在无法从关联中推断出名称时才使用它。 has_many:subscriber,:through =&gt; :订阅将寻找:订阅者或订阅者订阅者,除非给出:来源。
来自documentation:)