Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple before_action's in Rails controller?

I have two methods that I wish to run in several controller actions.

  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

How can I run both of them in actions action_a, action_b , only one in action_c and action_d, and none of them in action_e?

like image 836
Nimo Avatar asked Oct 24 '25 17:10

Nimo


1 Answers

You could probably do it like this:

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

Edit: colons were missing for the second line only and action_id

like image 78
IngoAlbers Avatar answered Oct 26 '25 08:10

IngoAlbers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!