ravip0711
ravip0711

Reputation: 511

Rails Devise: Should I use current_user or stick to User.find(params[:user_id])

I wanted to know when using Devise for my User model is there any difference in using @user = current_user.id vs @user = User.find(params[:user_id]) in my controllers and views(only current_user). What would be considered the "better" way.

Example:

  def index
    current_user
  end

or

  def index
    @user = User.find(current_user.id)
  end

or

 def index
   @user = User.find(params[:user_id])
 end

Upvotes: 0

Views: 749

Answers (2)

Artem Ankudovich
Artem Ankudovich

Reputation: 456

Devise creates current user as a session variable meaning you can use it in any view or controller.

How ever if user is not signed in you will get an error so as an example here are sign in / sign out buttons surrounded by an if statement to check whether current user is specified

<% if user_signed_in? %> 
//here we can use current_user for what ever you wish
    <a href="/users/sign_out" class="btn btn-primary">Logout</a>
    <a href="/users/edit/" class="btn btn-default">Edit Your profile</a>

    <% else %>
  // here we cant use current_user as it is not specified


    <a href="/users/sign_in" class="btn btn-primary">Sign in</a>
    <a href="/users/sign_up" class="btn btn-warning">Sign up</a>
    <% end %> 

Upvotes: 0

Graham Slick
Graham Slick

Reputation: 6870

Using

@user = User.find(current_user.id)

makes no sense, since, as you wrote above, you can use:

@user = current_user

However, @user = User.find(params[:user_id]) can be useful in some cases where you passe a user_id parameter (for example in a link_to or in a request.

Note that the params will not contain the user_id if you don't pass it manually. However, current_user will always be accessible

Upvotes: 1

Related Questions