【问题标题】:User Favorites - ActiveRecord::AssociationTypeMismatch用户收藏夹 - ActiveRecord::AssociationTypeMismatch
【发布时间】:2017-05-07 22:35:38
【问题描述】:

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

我正在尝试实现一项功能,允许用户从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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 参数表明@coffeeshop 不为空。我正在使用友好的 ids 宝石。 "method"=>"put", "authenticity_token"=>"WufNmDtpYuF1WaBeVuyPYt9cdWAbEw7ieMoHotrKnJ9WUJx0c0PJqvvact8FT+H1LPoxKXC8smQWYCjrzawY0w==", "type"=>"favorite", "id"=>"flatplanet"
    猜你喜欢
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多