2017-05-07 131 views
1

這個問題已經存在很多問題,但沒有一個能夠解決我的問題。用戶收藏夾 - ActiveRecord :: AssociationTypeMismatch

我想實現一個功能,允許用戶從這個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 

我意識到原來的問題是基於on 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

@coffeeshop爲空,你應該與用戶希望喜歡的(例如,從params[:id]檢索)的一個

+1

的初始化params表明@coffeeshop不爲null。我使用友善的ids寶石。 「方法」=> 「放」, 「authenticity_token」=> 「WufNmDtpYuF1WaBeVuyPYt9cdWAbEw7ieMoHotrKnJ9WUJx0c0PJqvvact8FT + H1LPoxKXC8smQWYCjrzawY0w ==」, 「類型」=> 「最愛」, 「ID」=> 「flatplanet」 –