0

I'm working implement vanity URLs based on the tutorial here: https://wesleyluyten.com/writing/vanity-urls-for-multiple-controllers-in-rails

To make vanity URLs work I need to use a rack router like so:

class SlugRouter
  def self.to(action)
    new(action)
  end
  def initialize(action)
    @action = action
  end
  def call(env)
    params = env['action_dispatch.request.path_parameters']
    params[:action] = @action

    sluggable = Slug.where('lower(url) = ?', params[:slug].downcase).first
    model = sluggable.try(:sluggable_type)
    raise ActionController::RoutingError.new('Not Found') if !model

    controller = [model.pluralize.camelize,'Controller'].join
    params[:controller] = model.pluralize.downcase
    controller.constantize.action(params[:action]).call(env)
  end
end

The problem is with raise ActionController::RoutingError.new('Not Found') if !model this is not gracefully handling routing errors. How can I gracefully handle routing error by redirecting to root w a flash message vs what is happening now is rails is showing an error page w

ActionController::RoutingError (Not Found):
lib/slug_router.rb:14:in `call'
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

1 Answers1

2

Try:

redirect_to root_path, notice: 'Unknown Route' if !model

Or:

if !model
  params[:controller] = 'index'
  IndexController.action('index').call(env)
else
  ...
end
Raj
  • 22,346
  • 14
  • 99
  • 142
  • is it possible inside a class which is not inherited from `ActionController::Base`? – rony36 Jan 05 '17 at 04:34
  • try the alternate solution I posted – Raj Jan 05 '17 at 04:43
  • I tried the alt solution. It did prevent the rails error message but ended up loading the the index with the incorrect URL, this would cause an SEO headache. How can I get it to simply redirect to a url like '/' or '/404' for seo purposes... thanks – AnApprentice Jan 05 '17 at 05:12
  • throw the Exception like earlier and handle it like this - http://stackoverflow.com/questions/25841377/rescue-from-actioncontrollerroutingerror-in-rails4 – Raj Jan 05 '17 at 05:26