用户收藏夹 - ActiveRecord::AssociationTypeMismatch

User Favorites - ActiveRecord::AssociationTypeMismatch

围绕这个已经存在很多问题,但是 none 完全解决了我的问题。

我正在尝试实现一项功能,允许用户从 Implement "Add to favorites" in Rails 3 & 4 中的答案中 'favorite' 咖啡店。但是当我尝试添加收藏夹时,我得到:

ActiveRecord::AssociationTypeMismatch (Coffeeshop(#70266474861840) expected, got NilClass(#70266382630600)):

user.rb

  has_many :coffeeshops
  has_many :favorite_coffeeshops # just the 'relationships'
  has_many :favorites, through: :favorite_coffeeshops, source: :coffeeshop

coffeeshops.rb

  belongs_to :user
  has_many :favorite_coffeeshops # just the 'relationships'
  has_many :favorited_by, through: :favorite_coffeeshops, source: :user

新模型加入关系

favorite_coffeeshops

class FavoriteCoffeeshop < ApplicationRecord
  belongs_to :coffeeshop
  belongs_to :user
end

coffeeshops.show.html.erb

<% if current_user %>
  <%= link_to "favorite",   favorite_coffeeshop_path(@coffeeshop, type: "favorite"), method: :put %>
  <%= link_to "unfavorite", favorite_coffeeshop_path(@coffeeshop, type: "unfavorite"), method: :put %>
<% end %>

coffeeshops_controller.rb

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

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

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

我意识到原来的问题是基于 Rails 3/4,而我现在是 5,所以我的代码中的某些内容现在可能已经过时了。

解决方案

coffeeshops_controller.rb

  def favorite
    @coffeeshop = Coffeeshop.find(params[:id]) #<= Added this
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @coffeeshop
      redirect_to :back, notice: "You favorited #{@coffeeshop.name}"

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

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

@coffeeshop 为 null,您应该用用户想要收藏的那个来初始化它(例如从 params[:id] 检索)