I am using devise and cancan with rails 3.2.1 and I’m having an unusual problem that I know can be refactored and simplified, but after much searching, I’m stuck.
I have first_name and last_name fields in the user model and have successfully displayed the full name of the user in the users/show.html.erb view using this code:
<%= @user.first_name + " " + @user.last_name %>
And I was successfully displaying a link to the user’s show page in the header using:
<% if user_signed_in? %>
<li><%= link_to @user.first_name + " " + @user.last_name, current_user %></li>
<% end %>
But, and I can’t figure this one out, after working on another part of the app, the header started giving me an undefined method error message…
In any case, I know there is a much better way to define and work with user names and I have tried some things out, such as adding a name method to the user model, but as you can clearly tell from this post, I am a beginner and have not been able to make that work.
Please let me know if you have any ideas on how to best work with users names in an application like this.
Where are you defining
@user? I’m willing to bet that it’s in your UsersController show action, which means it’s defined for your header in that action only.Try replacing your header code with this:
The trick is that Devise makes
current_useralways available when the user is signed in. You don’t have to worry about setting a@userinstance variable.