0

我有一个应用程序,其中有一个用户可以查看的预定义饮料列表。我试图让用户能够喜欢/不喜欢饮料。

出于某种原因,当我单击收藏链接时出现 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
4

1 回答 1

3

导致错误的那部分代码的 2 件事

  1. @drink 是一个数组,因此您需要遍历每个数组,然后再将它们添加到用户最喜欢的饮料列表中<<
  2. current_user.favorite_drinks << @drink - 你正在将一个Drink对象推到一张favorite_drinks桌子上,这就是你不匹配的原因

最好的解决方案是像这样设置你的模型

# user.rb
has_many :favorite_drinks
has_many :drinks, through: :favorite_drinks

# favorite_drink.rb
belongs_to :user
belongs_to :drink

# drink.rb
has_many :favorite_drinks
has_many :users, through: :favorite_drinks

这是假设你有一个user_idanddrink_idfavorites_drinks桌子上。然后你可以使用current_user.drink_ids = params[:drink_ids]

更新:

我刚刚注意到您正在使用params[:drink_id]. 所以将控制器代码更改为

@drink = Drink.find params[:drink_id]
current_user.drinks << @drink

你应该没事

更新:将@drink 移出 if 块,以便在不喜欢类型时仍然可以访问它

@drink = Drink.find params[:drink_id]

if type == "favorite"
  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
于 2013-02-26T01:44:26.803 回答