before_filter没被称为rails?

时间:2014-05-25 18:47:12

标签: ruby-on-rails ruby

我的友谊控制器中有一个名为request的通用CRUD之外的自定义方法。我的问题是我before_filter :require_auth设置为在FriendshipsController中的所有方法之前运行。

除了请求方法之外它工作正常。

(这让我觉得它与普通的CRUD有关吗?)

当我现在调用请求方法时,它会跳过:require_auth并直接转到请求方法,这会给我带来错误,因为我在请求方法中定义了:require_auth中需要的一些变量。

这是我的FriendshipsController

class FriendshipsController < ApplicationController

  skip_before_filter :verify_authenticity_token, :only => [:create]

  before_filter :require_auth

  def create
    @friendship = Friendship.new(user_id: params[:user_id], friend_id: params[:friend_id], status: params[:status])

    if @friendship.save
      render :status => 200, :json => {:message => "Friendship Created"}
    else
      render :status => 500, :json => { :message => "Problem creating friendship" }
    end
  end

  def request
    # friendID = params[:friend_id]
    # userID = @currentuser.id
    binding.pry
    @userid = @currentuser.id
    @friendid = params[:friend_id]
    unless (@userid == @friendid || Friendship.exists?(user_id: @userid,friend_id: @friendid))
      create(:user_id => userID, :friend_id => friendID, :status => 'pending')
      create(:user_id => friendID, :friend_id => userID, :status => 'requested')
    end
  end

end

以下是ApplicationController,我定义了require_auth

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  # protect_from_forgery with: :null_session

  def require_auth
    binding.pry
    auth_token = request.headers["HTTP_AUTH_TOKEN"]
    @user = User.find_by_auth_token(auth_token)
    if @user.auth_token
      @currentuser = @user
    else
      render :status => 401, :json => {:error => "Requires authorization"}
      return false
    end
  end

end

1 个答案:

答案 0 :(得分:1)

克里斯彼得斯在评论中是正确的。我的问题是rails已经定义了请求。我简单地将方法名称更改为其他名称并且它有效。

感谢。