cjm2671
cjm2671

Reputation: 19476

Rails routes logic

Is it OK to put custom logic in routes.rb?

For example:

unless current_user
  root :to => anonymous_page
else
  root :to => logged_in_page
end

Upvotes: 5

Views: 967

Answers (3)

Puhlze
Puhlze

Reputation: 2614

You can use the clearance gem to do what you're thinking. From the clearance documentation:

Blog::Application.routes.draw do
  constraints Clearance::Constraints::SignedIn.new { |user| user.admin? } do
    root to: 'admin'
  end

  constraints Clearance::Constraints::SignedIn.new do
    root to: 'dashboard'
  end

  constraints Clearance::Constraints::SignedOut.new do
    root to: 'marketing'
  end
end

This works because clearance adds itself into the middleware stack, making signed in status available before routes are processed.

Upvotes: 0

Taryn East
Taryn East

Reputation: 27747

You can put custom logic into routes... but as avenger suggested - "current_user" won't work due to when the routes file is loaded. We sometimes use logic in our routefile (eg setting up routes that are only available if RAILS_ENV == 'development').

What you probably want is a before_filter on "anonymous_page" eg:

before_filter :redirect_if_logged_in, :only => :anonymous_page

def redirect_if_logged_in
  redirect_to logged_in_page if current_user.present?
end

Upvotes: 2

wanderfalke
wanderfalke

Reputation: 878

That doesn't work like that. Routes are read / created at server startup, not on per request basis. Such logic you have to put into controllers.

Upvotes: 2

Related Questions