How to shorten access to the current user view in Rails?

How can I use root to display the current user in a Rails application?

I want to do something like

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

but how do I pass the current user id?

thanks

+6
source share
4 answers

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 
+4
source

I did before_filter , where I check if request.path == root_path , and if so, I redirect the path, which should be the user root. The root path set in routes.rb is not a user root for any user, so there is no endless redirection. Just make flash.keep so that your flash messages can withstand redirection.

EDIT: Reading Q&A and comments, trying to figure out what you already have, and what you still need. Did you manage to configure routing to get the show action displayed without :id in the url? If possible, you need something like this in your show control:

 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 
+8
source

Is it always the "current" user or any arbitrary user?

If this is the current user, just send them all to one page (without specifying an identifier) ​​and in the controller’s action get the current user (from the session, etc.) and pass it to the view.

+1
source

The current user ID should not be in the URL that should be stored in the session. Therefore, you do not need to transfer it to the route.

Edit: After reading your comment, I think you could define another action, such as profile , to display the current user view.

Or in your users/show action, add the following code:

 if current_user.is_admin? @user = User.find params[:id] else @user = current_user end 
0
source

Source: https://habr.com/ru/post/911179/


All Articles