Is there a better way cancel the current request and redirect to an error page in Rails?

CaTs

New Member
#1
Frequently when I'm dealing with controllers I have found the need to stop the current action and then show an error page. Currently I have a method to show my error page in application controller:
Mã:
class ApplicationController < ActionController::Base

  def show_error msg
    render file: 'public/404.html', message: msg, layout: false
  end

end
And then from another controller I can use it like this:
Mã:
class BikesController < ApplicationController

  def inspect
    @bike = Bikes.find(params[:id])
    show_error("You can't inspect a bike without wheels!") and return unless @bike.hasWheels?       
    @similar_bikes = Bikes.similar_to(@bike)
    render "inspect"
  end

end
However I dislike having to include and return alongside my show_error method to ensure that nothing else is executed. Is there a cleaner way to do this without using return?
 

Admin

Administrator
Thành viên BQT
#2
The Rails-way of handling situations like that is throwing an exception and handling it.
Mã:
# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  class NotFoundError < StandardError; end

  rescue_from NotFoundError do |e|
    render file: "#{RAILS_ROOT}/public/404.html", message: e.message, layout: false, status: :not_found
  end

  ...
end
raise NotFoundError, msg in any action of ApplicationController or its child stops the action and renders your 404.html file, returning HTTP Error 404.
 
Top