Best way to handle nil attributes?

17 views
Skip to first unread message

David Williams

unread,
Feb 7, 2016, 3:12:47 PM2/7/16
to rubyonra...@googlegroups.com
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.

<h2><i class="fa fa-street-view"></i> <% if @user.profile.location.nil?
? "" : @user.profile.location %> <% end %></h2>

OR

<% if @user.profile.location.present? %>
<h2><i class="fa fa-street-view"></i>Location <%=
@user.profile.location %></h2>
<% end %>

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Feb 7, 2016, 3:16:34 PM2/7/16
to Ruby on Rails: Talk
On 7 February 2016 at 20:11, David Williams <li...@ruby-forum.com> 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.
>
> <h2><i class="fa fa-street-view"></i> <% if @user.profile.location.nil?
> ? "" : @user.profile.location %> <% end %></h2>

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

Colin

David Williams

unread,
Feb 7, 2016, 3:37:36 PM2/7/16
to rubyonra...@googlegroups.com
Colin Law wrote in post #1181246:

>>
>> <h2><i class="fa fa-street-view"></i> <% if @user.profile.location.nil?
>> ? "" : @user.profile.location %> <% end %></h2>
>
> You are testing @user.profile.location for nil, but it is
> @user.profile that is nil
>
> Colin

Doh!Thanks. I fixed it now.
Reply all
Reply to author
Forward
0 new messages