I have statements such as @user = User.find(current_user.id) throughout my application.
Sometimes a user might enter with a nil variable (such as a new user for whom current_user is nil).
I’m sure the dumb way to do this would be to scatter if statements everywhere like…
if current_user.exists?
@user = User.find(current_user.id)
else
redirect_to root_url
---*or*---
@user = "new" # for use with if/case statements later on
end
What is the elegant way to deal with this confusion?
@user = User.find(current_user.id)is a little unnecessary. Mostly because current_user is a User object already, so at the very least you should do@user = current_user, but I would recommend that if it isn’t already done by the authentication framework, I would add this to you application controller:That will make the
current_userobject available to your views and render the@userobject unnecessary.For handling redirects, I usually have this in my application controller:
And then in my controllers that don’t want to redirect:
Regarding setting the user to new, I wouldn’t do it. I generally like my
Userobjects to be user objects. I would just test for a new user byif current_userwhere a nil current_user is the same as setting it to ‘new’.I hope this helps