尝试在未定义的地方使用current_user

| 我的投票模型中有这个电话:
 fires :vote_updated, :on => :update,
                   :actor => :user,
                   :secondary_subject => :video,
                   :if => lambda { |vote| ((vote.value == 1) || (vote.value == -1)) && (vote.video.user != current_user)}
如果您不熟悉,它可与timeline_fu插件一起使用。 如果拥有投票视频的用户是当前用户,我不希望触发该呼叫。这是该行的来源:
:if => lambda { |vote| ((vote.value == 1) || (vote.value == -1)) && (vote.video.user != current_user)}
但是,我这里没有访问
current_user
。我该如何解决? 这是我的投票控制器中的create方法(实际上没有更新方法):
def create       
  @video = Video.find(params[:video_id])
  @vote = current_user.video_votes.find_or_create_by_video_id(@video.id)

  if @vote.value.nil?
    if params[:type] == \"up\"
      @vote.value = 1
    else
      @vote.value = -1
    end
  elsif (params[:type] == \"up\" && @vote.value == 1) || (params[:type] == \"down\" && @vote.value == -1)
    @vote.value = 0
  elsif ((params[:type] == \"up\" && @vote.value == -1) || (params[:type] == \"down\" && @vote.value == 1)) || (@vote.value == 0)
    if params[:type] == \"up\"
      @vote.value = 1
    else
      @vote.value = -1
    end
  end  

  if @vote.save
    respond_to do |format|
      format.html { redirect_to @video }
      format.js
    end
  else
    respond_to do |format|
      format.html
      format.js
    end
  end  
end
    
已邀请:
我相信正确的做法是在控制器中对此进行验证。我将为这种情况创建一个前置过滤器 更新: 举个简单的例子:
before_filter :valid_vote, :only => :update

def update
   @vote.update_attributes(params[:vote]) # or whatever
end
..

private

def valid_vote
   @vote = Vote.find params[:id]
   unless ( @vote.video.user.id != current_user.id )
      render :text => \'You can\'t vote for your own video\', :status => 403
   end
end
因此,在执行\'update \'操作之前,先声明并验证@vote。 如果无效,那么您的“更新”操作将保持不变 更新2: 不确定自己的喜好如何,但您也可以按照以下步骤操作: 在您的投票模型中:
attr_accessor :skip_timeline
然后将这个概念与before过滤器一起使用,但请执行
@vote.skip_timeline = true
而不是呈现文本 那么该语句可能如下所示:
:if => lambda { |vote| ((vote.value == 1) || (vote.value == -1)) && !vote.skip_timeline }
您也可以将
((vote.value == 1) || (vote.value == -1))
移到之前的过滤器中:
def valid_vote
   @vote = Vote.find params[:id]
   unless ( [1,-1].include? @vote.value && @vote.video.user.id != current_user.id )
       @vote.skip_timeline = true
   end
end
和 :if => lambda {|投票| !vote.skip_timeline}     
您收到此错误,是因为通常不建议您在模型中访问current_user(或会话信息)。我不太熟悉timeline_fu gem,因此此答案不会成为您可能得到的最大答案。我只是向您展示如何从任何模型访问current_user。 首先转到您的应用程序控制器。您需要创建一个设置当前用户的方法。您需要在before过滤器中调用方法。
before_filter :loadCurrentUser 

def loadCurrentUser
  User.currentUser = current_user
end
然后,在用户模型中,您需要定义\'currentUser \'。
def self.currentUser
   Thread.currentUser[:user]
end
您不一定必须在应用程序控制器中声明current_user,但是由于它是gem,因此我不确定它是否具有易于访问的控制器。 编辑:这种方式可能容易出现问题,但是我不确定是否要问如何使current_user在模型中可用,或者是一种完全不同的解决方法,以便您没有问题...并阅读另一个答案,我想这不是您要的。     

要回复问题请先登录注册