2016-03-25 1 views
-2

私のコントローラでこの問題が発生しましたが、何が起こっているのか分かりません。 Like::ActiveRecord_AssociationRelationの定義されていないメソッドtoggle!を返します:または私の作成アクションでは、すべてのものが動作しますが、更新アクションでは動作しません。 これは、イベント、誰かのように好き嫌いをするコントローラのような基本的なものです。未定義のメソッド `toggle! ' #:ActiveRecord_AssociationRelation:

class LikesController < ApplicationController 

    before_action :authenticate_user! 

    def create 
    @project=Project.find(params[:project_id]) 
    @like= @project.likes.where(user:current_user).first_or_initialize(name:current_user.first_name) 
    @like.toggle(:heart) 
    @like.save 
    Notification.create(user:current_user, user_name: current_user.first_name, action:'like', recipient:@project.subject) 
    redirect_to project_path(@project) 
    end 



    def update 
    @project=Project.find(params[:project_id]) 
    @like= @project.likes.where(user:current_user) 
    @like.toggle(:heart) 
    @like.save 
    Notification.create(user:current_user, user_name: current_user.first_name, action:'Unlike', recipient:@project.subject) 
    redirect_to project_path(@project) 
    end 
end 
+0

を:: '@ = @ project.likes.whereのような(CURRENT_USERユーザー)うまく動作します。 –

+0

あなたは '@ like.first.toggle(:heart)'や 'Like.toggle(:heart)'で切り替える必要があります。 –

答えて

1

toggleは基本的にクラスメソッドです。あなたはActiveRecord::Relationオブジェクトでそれを呼び出すことはできません。最初にオブジェクトを分離する必要があり、次にすべてをtoggleにすることができます。

あなたが好きなオブジェクトを取得する方法のようにfirstlastまたはその他を呼び出すことができます。.first`がすべき本だと思い

@project.likes.where(user: current_user).first 
+0

皆さん、ありがとうございました。 –

関連する問題