我正在Implement "Add to favorites" in Rails 3 & 4中概述的Rails应用程序中构建收藏夹系统,但是我一直遇到以下错误。
RecipesController#favorite中的ActiveRecord :: AssociationTypeMismatch 预期配方(#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
任何想法可能是什么原因造成的?
答案 0 :(得分:0)
根据@Зелёный的评论,在控制器中定义了“ @recipe”变量,但在“收藏夹”方法中需要将其定义为“ @recipe = Recipe.find(params [:id])”。 / p>