Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to root to the current user's show view in Rails?

How can I root to the current user's show view in a Rails app?

I want to do something like

authenticated :user do
    root :to => "users#show"
end

but how do I pass the current user's ID into this?

Thanks

like image 453
Andy Harvey Avatar asked Mar 20 '12 07:03

Andy Harvey


People also ask

How do you check if a user is signed in rails?

Take a look at controller filters and helpers in Devise documentation. You can filter your actions in your controller with this method to ensure only logged-in users can process a given action or all actions in a controller, else if user isn't logged-in then he is redirect to login page. Save this answer.

What is root in Ruby on Rails?

Root Routes Setting the Root Page of the AppThe root webpage is the one that displays for requests that include only the domain/port part of the URL and not the resource path (e.g., http://localhost:3000/). The root webpage is often thought of as the default page for the web app.


2 Answers

I did a before_filter where I check if request.path == root_path and if so I redirect to the path that should be user-specific root. The root_path set in routes.rb is not user-specific root for any user so there is no infinite redirection. Just do flash.keep to make your flash messages survive the redirection.

EDIT: Reading Q&A and comments, trying to understand what you already has, and what you still need. Did you succeed to setup routing to get show action rendered without the :id in the URL? If so maybe you need something like this in your controller show action:

if params[:id].nil? # if there is no user id in params, show current one
    @user = current_user
else # if there is the user id in params just use it, 
     # maybe get 'authorization failed'
    @user = User.find params[:id]
end
like image 71
wrzasa Avatar answered Nov 18 '22 19:11

wrzasa


The following worked for me.

In routes.rb:

root to: 'users#current_user_home'

In users_controller.rb:

def current_user_home
  redirect_to current_user
end
like image 22
Greg Blass Avatar answered Nov 18 '22 19:11

Greg Blass