未定义的方法`切换!' for#:ActiveRecord_AssociationRelation:

时间:2016-03-25 11:29:00

标签: ruby-on-rails

我刚刚在我的控制器中遇到这个问题,我不明白发生了什么。 它为toggle!返回一个未定义的方法Like::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

1 个答案:

答案 0 :(得分:1)

toggle基本上是一种类方法;你无法在ActiveRecord::Relation对象上调用它。您需要首先隔离对象,然后您可以toggle

您可以拨打firstlast或任何其他类似方法来获取以下对象:

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