ruby-on-rails - 有_许多 :through association error 'could not find the source association'

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

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

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

ActiveRecord::HasManyThroughSourceAssociationNotFoundError in GuidelinesController#favourite Could not find the source association(s) :favourite or :favourites in model FavouriteGuideline. Try 'has_many :favourites, :through => :favourite_guidelines, :source => '. Is it one of :guideline or :user?

    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

指南 Controller 中我最喜欢的操作是:

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

最佳答案

好的,

Try 'has_many :favourites, :through => :favourite_guidelines, :source => '. Is it one of :guideline or :user?

这是:指南。

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

:source Specifies the source association name used by has_many :through queries. Only use it if the name cannot be inferred from the association. has_many :subscribers, :through => :subscriptions will look for either :subscribers or :subscriber on Subscription, unless a :source is given.

来自 documentation :)

关于ruby-on-rails - 有_许多 :through association error 'could not find the source association' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840344/

相关文章:

ruby-on-rails - Mongoid 使用 has_one 将一个对象与同一类的两个不同对象相关联

css - 备用列 (<td>) 类,甚至可能是 Rails 中的列内容?

ruby - 未定义方法 add_to_base

ruby-on-rails - 未指定端点的永久重定向 s3

ruby-on-rails - 如何定义rescue_from后备处理程序?

ruby-on-rails - Errno::ENOENT: 没有这样的文件或目录@rb_sysopen -/tmp/

ruby-on-rails-3 - 导轨 3 : how to render text file in-line?

ruby-on-rails-3 - 从轻便摩托车::集合中删除的更新 - NoMethodError:#<Moped::Collection 的未定义方法 `update'

javascript - 如何使用 Cucumber 测试用 javascript 加载的内容

ruby-on-rails - 事件记录错误消息form_tag Rails 3