I have a project instance with a nested task. If i debug project.task i got what i expect:
# debug result
--- !ruby/object:Task
attributes:
id: 1
name: XYZ
If i want to debug project.task.name i got the error message “undefined method `name’ for nil:NilClass”.
# this works
<% @projects.each do |project| %>
<%= project.name %><br/>
<%= debug project.task %>
<% end %>
# this does not work
<% @projects.each do |project| %>
<%= project.name %><br/>
<%= debug project.task.name %>
<% end %>
The first one works because if you execute :
and there is a project but there is no task, you get nil.
However, when you execute :
You get an exception if task is nil, since it cannot find the name attribute. However, you can force it to return nil if a task is not there, by using the rails try method :