已经存在很多问题,但是没有一个完全解决我的问题。
我正在尝试实现一项功能,允许用户从本机构中的答案中"喜欢"的咖啡店"添加到收藏夹"中。在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
咖啡馆.rb
belongs_to :user
has_many :favorite_coffeeshops # just the 'relationships'
has_many :favorited_by, through: :favorite_coffeeshops, source: :user
加入关系的新模型
faly_coffeeshops
class FavoriteCoffeeshop < ApplicationRecord
belongs_to :coffeeshop
belongs_to :user
end
咖啡馆.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 %>
咖啡馆_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中,所以也许现在我的代码已经过时了。
解决方案
咖啡馆_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]
检索(