【发布时间】: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