I have a very simple user model. When I first created it, it had three fields email
, password_hash
, and password_salt
.
I recently added a field to that model, in order to allow the user to set a display name, the field being called display
. I used the method as outlined in this answer. So what I typed into terminal would look like this:
script/rails g migration add_display_to_users display:string
and then
rake db:migrate
This worked fine, and after modifying my signup form, I was able to add this data into the database.
In my application layout, I then want to display the user's display name in the header. So, in my application controller, there is a method I call in every controller in order to get the nav bar, called nav_bar
. In this method I also set a @user
instance variable, if they are logged in.
Because the nav_bar
method is called in the application controller, I can then access it from the application layout. So, I tried to show their email in the header as a test, like so:
<% if @user %>
<div class="ac_button">
<%= @user.email %>
</div>
<% end %>
This works fine, and displays their email in the header. However, if I change it to
<%= @user.display %>
It doesn't display anything.
The strangest part, is if I call @user.email
, or any other property of the user somewhere in my application controller or layout. It works, and shows their display name. I have no idea why that would make it work, but it does.
For example, if after finding the user in the application controller, I call @user.email
, it will then show their display name in the layout fine.
def nav_bar
if session[:user_id]
@user = User.find(session[:user_id])
@user.email
end
# create and return the navbar
end
Or if in the layout, I call a property of the user anywhere, it also works.
<div class="ac_button">
<% @user.password_hash %>
<%= @user.display %>
</div>
If anyone can explain this very strange behavior I will be amazed!