Question

On my user profile page in my rails app, I am recieving the error:

undefined method `title' for nil:NilClass

I know it is because of the following 3 lines of code:

<% if @user.profile.title %>
     <%= @user.profile.title %>
<% end %>

I don't understand why. Since i use the if statement, shouldn't it first check whether title exists, then if it exists display it, and if it does not exist, it should not display it. What is wrong and how do I fix it? Thanks.

Was it helpful?

Solution

Since title is nil you can't test against it like you did. Try:

<% if @user.profile.try(:title) @user.profile.title %>

OTHER TIPS

You can do:

<% if @user.profile.present? %>
  <%= @user.profile.title %>
<% end %>

Or with try:

<%= @user.profile.try(:name) %>

With a default value if no profile associated:

<%= @user.profile.try(:name) || 'No profile for this user' %>

Because it is not correctly. If you want to get access to some parameter from user you have to use direct access. But if you want to use profile that belongs to User model look at this link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top