我有一个应用程序,其中有一个用户可以查看的预定义饮料列表。我试图让用户能够喜欢/不喜欢饮料。
出于某种原因,当我单击收藏链接时出现 AssociationMismatch 错误。显然代码不喜欢我的 current_user.favorite_drinks << @drink 部分代码
CONTROLLER Drinks_controller.rb
def favorite
type = params[:type]
if type == "favorite"
@drink = Drink.find params[:drink_id]
current_user.drinks << @drink
redirect_to :back, notice: 'You favorites #{@drink.name}'
elsif type == "unfavorite"
current_user.drinks.delete(@drink)
redirect_to :back, notice: 'You unfavorited #{@drink.name}'
else
redirect_to :back, notice: 'Nothing happened'
end
end
控制器收藏夹_controller.rb
def show
@user = User.find(params[:id])
if @user
@drinks = @user.favorite_drinks.all
render action: :show
else
render file: 'public/404', status: 404, formats: [:html]
end
end
路线路线.rb
匹配 'auth/:provider/callback', to: 'sessions#create' match 'auth/failure', to: redirect('/') match 'signout', to: 'sessions#destroy', as: 'signout'
根到:“drinks#index”资源:眼镜资源:成分资源:内阁资源:饮料确实得到“最喜欢的”,:on =>:收集结束资源:最喜欢的
获取“收藏夹/节目”
模型用户.rb
has_one :cabinet
has_many :favorite_drinks
has_many :drinks, through: :favorite_drinks
模型 favourite_drink.rb
attr_accessible :drink_id, :user_id
belongs_to :user
belongs_to :drink
查看_results.html.haml
%td= link_to "favorite", favorite_drinks_path(drink_id: drink.id, type: "favorite"), method: "get"
%td= link_to "unfavorite", favorite_drinks_path(drink, type: "unfavorite"), method: "get"
查看收藏夹/show.html.haml
%table.table.table-striped
%thead
%tr
%th Name
%tbody
- if @drinks.each do |drink|
%tr
%td= link_to drink.name, drink
我的更新代码
迁移 create_favorite_drinks.rb
class CreateFavoriteDrinks < ActiveRecord::Migration
def change
create_table :favorite_drinks do |t|
t.integer :drink_id
t.integer :user_id
t.timestamps
end
end
end