Best way to handle nil attributes?

Hello to my fellow rails devs.

I’m currently receiving an “undefined method `location’ for
nil:NilClass” exception error in one of my views when the user hasn’t
filled in the form for their profile.

How would I approach bypassing this error in the cleanest way?

I’ve tried to use the method below, but the error still persist.

<% if @user.profile.location.nil? ? "" : @user.profile.location %> <% end %>

OR

<% if @user.profile.location.present? %>

Location <%=
@user.profile.location %>


<% end %>

On 7 February 2016 at 20:11, David W. [email protected]
wrote:

Hello to my fellow rails devs.

I’m currently receiving an “undefined method `location’ for
nil:NilClass” exception error in one of my views when the user hasn’t
filled in the form for their profile.

Read the error carefully, it says you have called location on
something that is nil.

How would I approach bypassing this error in the cleanest way?

I’ve tried to use the method below, but the error still persist.

<% if @user.profile.location.nil? ? "" : @user.profile.location %> <% end %>

You are testing @user.profile.location for nil, but it is
@user.profile that is nil

Colin

Colin L. wrote in post #1181246:

<% if @user.profile.location.nil? ? "" : @user.profile.location %> <% end %>

You are testing @user.profile.location for nil, but it is
@user.profile that is nil

Colin

Doh!Thanks. I fixed it now.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs