用户收藏夹 - ActiveRecord :: AssociationTypeMismatch

时间:2017-05-07 22:35:39

标签: ruby-on-rails ruby activerecord model-associations

围绕此问题已经存在很多问题,但没有一个能解决我的问题。

我正在努力实现一项功能,允许用户在此Implement "Add to favorites" in Rails 3 & 4的答案中“喜欢”咖啡店。但是当我试图添加我最喜欢的:

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

0 个答案:

没有答案