【问题标题】:has_many :through association error 'could not find the source association'has_many:通过关联错误'找不到源关联'
【发布时间】:2026-02-20 09:10:01
【问题描述】:

我有三个模型:user、guideline 和 favourite_guideline(目的是用户可以创建自己喜欢的指南列表)。

我在尝试添加收藏夹时遇到关联错误

ActiveRecord::HasManyThroughSourceAssociationNotFoundError 在 指南控制器#favourite 找不到源关联 :favourite 或 :favourites in 模型收藏指南。试试 'has_many :favourites, :through => :favourite_guidelines, :source => '。是 :guideline 还是其中之一 :用户?

    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

【问题讨论】:

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


    【解决方案1】:

    好的,

    试试 'has_many :favourites, :through => :favourite_guidelines, :source => '。它是 :guideline 还是 :user 之一?

    它是:指南。

    has_many :favourites, through: :favourite_guidelines, source: :guideline
    

    :来源 指定 has_many :through 查询使用的源关联名称。仅当无法从关联中推断名称时才使用它。 has_many :subscribers, :through => :subscriptions 将在 Subscription 上查找 :subscribers 或 :subscriber,除非给出 :source。

    来自documentation :)

    【讨论】:

    • 谢谢 - 这仍然给出相同的错误信息。我注意到错误标题是 'ActiveRecord::HasManyThroughSourceAssociationNotFoundError in GuidelinesController#favourite' - 我已将最喜欢的操作复制到上面的问题中,以防出现问题...
    最近更新 更多