Rails 应用程序中的关联类型不匹配错误

Association Type Mismatch Error in Rails App

我正致力于在 rails 此处概述的应用程序中构建一个收藏系统 Implement "Add to favorites" in Rails 3 & 4 但是我一直 运行 出现以下错误。

RecipesController 中的 ActiveRecord::AssociationTypeMismatch#favorite Recipe(#106776840) 预期,得到 nil,它是 NilClass(#21446380)

的一个实例
type = params[:type]
    if type == "favorite"
     current_user.favorites << @recipe_id
     redirect_to :back, notice: 'You favorited #{@recipe.title}'

    elsif type == "unfavorite"

我的代码如下

配方模型

class Recipe < ApplicationRecord
    has_many :ingredients, dependent: :destroy
    has_many :steps, dependent: :destroy
    has_many :favorite_recipes
    has_many :favorited_by, through: :favorite_recipes, source: :user

    validates :title, presence: true

    def self.search(search)
        where("title LIKE ? OR creator LIKE ? OR description LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%") 
    end
end

用户模型

class User < ApplicationRecord
    has_secure_password
    has_many :favorite_recipes
    has_many :favorites, through: :favorite_recipes, source: :recipe
end

最喜欢的食谱模型

class FavoriteRecipe < ApplicationRecord
    belongs_to :recipe
    belongs_to :user
end

配方控制器

class RecipesController < ApplicationController

    def favorite
        type = params[:type]
        if type == "favorite"
         current_user.favorites << @recipe
         redirect_to :back, notice: 'You favorited #{@recipe.title}'

        elsif type == "unfavorite"
         current_user.favorites.delete(@recipe)
         redirect_to :back, notice: 'Unfavorited #{@recipe.title}'

        else
            # Type missing, nothing happens
            redirect_to :back, notice: 'Nothing happened.'
        end
    end
end

路线

Rails.application.routes.draw do
  resources :recipes do
    resources :ingredients, :steps
    put :favorite, on: :member
  end

  resources :users

end

知道是什么原因造成的吗?

根据@Зелёный 的评论,控制器中定义了“@recipe”变量,但需要在 "favorite"方法。