Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails early return if before_action attribute set fails

I would like to perform a db lookup using the incoming request's remote_ip before any controller method is hit in order to set a particular controller class attribute. However if the lookup fails (if no object is linked to the request IP) I would like to immediately return a 404 response.

For example:

class Controller < ApplicationController
   before_action :set_instance_or_404

   def index
     # do something with @instance
   end

   private
     def set_instance_or_404
       @instance = Model.find_by(ip_address: request.remote_ip)
       # or if no instance is found, immediately return a 404 without hitting "index" method (or any other method for that matter)
     end
end

Any help will be greatly appreciated!

like image 768
Arnoux Avatar asked Oct 19 '25 14:10

Arnoux


1 Answers

You can raise an ActiveRecord::RecordNotFound exception, which will stop the action and return a 404. Or you can render or redirect which will also stop the action. See Rails Filters docs. Here are examples of each.

class Controller < ApplicationController
  before_action :set_instance_or_404

  def index
    # do something with @instance
  end

  private
    def set_instance_or_404
      @instance = Model.find_by(ip_address: request.remote_ip)
      raise ActiveRecord::RecordNotFound unless @instance # returns 404
    end
end

class Controller < ApplicationController
  before_action :set_instance_or_404

  def index
    # do something with @instance
  end

  private
    def set_instance_or_404
      @instance = Model.find_by(ip_address: request.remote_ip)
      render(status: 404, inline: "Instance not found") unless @instance 
    end
end
like image 50
Bill Doughty Avatar answered Oct 22 '25 04:10

Bill Doughty



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!