在Rails控制器中有多个before_action?

时间:2015-05-28 11:39:03

标签: ruby-on-rails controller

我希望在几个控制器操作中运行两种方法。

  def get_offer
    @offer = Offer.find_by :uuid => params[:offer_id]
    if @offer.blank?
      error_response = ErrorResponse.new("Offer not found")
      render json: error_response, :status => :not_found and return
    end
  end

  def validate_api_v2
    api_version = params[:api_version]
    if api_version != api_version_to_validate
      error_response = ErrorResponse.new("API version not supported")
      render json: error_response, :status => :bad_request and return
    end
  end

如何在action_aaction_baction_caction_d中只有一个,action_e中没有一个?

5 个答案:

答案 0 :(得分:2)

你可能会这样做:

before_action :get_offer, only: [:action_a, :action_b, :action_c]
before_action :validate_api_v2, only [:action_a, :action_b, action_d]

答案 1 :(得分:1)

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaS*************************"> </script> get_offer移至validate_api_v2,然后移至其他控制器,例如您可以执行以下操作:

ApplicationController

class SomeController < ApplicationController
  before_filter :get_offer, :validate_api_v2, :only => [:action_a, :action_b]
end

我希望你明白这一点。

答案 2 :(得分:1)

在控制器关注中编写方法。例如:

# app/controllers/concerns/example_concern.rb
module ExampleConcern
 extend ActiveSupport::Concern

 protected
 def get_offer
   @offer = Offer.find_by :uuid => params[:offer_id]
   if @offer.blank?
     error_response = ErrorResponse.new("Offer not found")
     render json: error_response, :status => :not_found and return
   end
 end

 def validate_api_v2
   api_version = params[:api_version]
   if api_version != api_version_to_validate
     error_response = ErrorResponse.new("API version not supported")
     render json: error_response, :status => :bad_request and return
   end
 end
end

现在在控制器中,将模块包含在关注点中,并根据需要使用before_action调用方法。例如:

# app/controllers/examples_controller.rb
class ExamplesController < ApplicationController
  include ExampleConcern

  before_action :get_offer, only: [:action_a, :action_b, :action_c]
  before_action :validate_api_v2, only: [:action_a, :action_b, :action_d]

  def action_a
  end
  def action_b
  end
  def action_c
  end
  def action_d
  end
  def action_e
  end
end

答案 3 :(得分:0)

except在某些情况下派上用场:

before_action :get_offer, only: [:action_a, :action_b, :action_c]
before_action :validate_api_v2, except: [:action_e, :action_c] 

答案 4 :(得分:0)

试试这个

 function result(){
      if( $("#f2").val() > $("#f1").val()*5 ) $("#f2").val($("#f1").val()*5);
    }

    $("#f1").keyup(result).change(result);
    $("#f2").keyup(result).change(result);