Verdi Erel Ergün
Verdi Erel Ergün

Reputation: 1051

How to have multiple paths display URL as root

I want users#new and tasks#index to display as the root path URL, i.e. / When a user logs in on the path users#new (set as root) they are redirected to tasks#index and URL does not change. Can this be done in the routes.rb file?

This is my routes.rb file:

Todo::Application.routes.draw do
  resources :sessions 
  resources :subscriptions
  resources :users
  resources :tasks do
    collection do
      post :sort
    end
  end
  root :to => "users#new"
  match "sessions#new" => "tasks#index"
  match "sessions#" => "tasks#index"

Upvotes: 1

Views: 1123

Answers (2)

phoenix12
phoenix12

Reputation: 23

I have just found routes definitions by constraints

in your routes.rb file

class LoggedInConstraint
  def initialize(value)
     ...
  def matches?(request)
      request.cookies.key?("user_token") == @value
    end
  end
end

RedmineApp::Application.routes.draw do
  root :to => "static#home", :constraints => LoggedInConstraint.new(false)
  root :to => "users#show", :constraints => LoggedInConstraint.new(true)
  ....
end

It's described here: http://collectiveidea.com/blog/archives/2011/05/31/user-centric-routing-in-rails-3/

Upvotes: 1

Andrew Kuklewicz
Andrew Kuklewicz

Reputation: 10701

I'm not sure I would actually do this,but assuming you map the root tasks#index, you could also use a before filter to render the sessions#new template when the user is not logged in:

class TasksController < ApplicationController

  before_filter :authorize_access

  def authorize_access
    unless logged_in?
      render :template => 'sessions/new'
      return false  #I don't remember if you need this still or not
    end
  end

  def index
    @tasks = Task.all
  end

end

To be clear, when a user requests "/", Rails will route this request to a single controller and action. You can map multiple paths to the same controller/action, but a single path is deterministic to a particular controller/action. IOW - it is not logically possible in routes to have a get request for any path, root or otherwise, go to more than one controller/action.

Users don't see a controller and action though, they see the result of what the action renders, usually based on some template, and that you can determine in the action (or a controller filter's) logic, as I did above.

You could also create a 3rd controller, a RootController, that contains the logic to display the list of tasks or a login page based on if the user is logged in.

Upvotes: 1

Related Questions