Я работаю над созданием подходящей системы в приложении rails, описанном здесь Реализация "Добавить в избранное" в Rails 3 и 4 , однако я продолжаю сталкиваться со следующей ошибкой.
ActiveRecord:: AssociationTypeMismatch в RecipesController # любимый рецепт (# 106776840) ожидается, получил ноль, который является экземпляром 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
Есть идеи, что может быть причиной этого?