hellomello
hellomello

Reputation: 8597

Ruby on Rails: Trying to understand Undefined method, nil:NilClass

I'm trying to understand how I'm getting two different outputs from rails

If I have this:

<%= if value.user.present?
  link_to value.user.email, value.user 
end %>

I gives me what I wanted. It out puts the email of the user with its link associated with it. But when I take the if statement out,

<%= link_to value.user.email, value.user %>

I get this error.

undefined method `email' for nil:NilClass

I don't get it? Aren't I just doing the same thing with the first statement? It outputs the link_to.

Why am I get two different outputs with what I thought was the same statement?

Upvotes: 0

Views: 186

Answers (3)

Mark Swardstrom
Mark Swardstrom

Reputation: 18110

That's happening because you called a method on nil (value.user is nil)

An easy way to shorten it up...

<%= link_to(value.user.email, value.user) if value.user %>

A note, if value.user could be nil (not false), but is still considered 'falsey' in ruby.

Upvotes: 3

muttonlamb
muttonlamb

Reputation: 6501

This error would pop up if any of your value.user items do not have an email associated.

I've encountered this when migrating and not all rows have the item assigned.

Upvotes: 0

rank
rank

Reputation: 83

in your if condition it checks whether your user is present and if present it will give the proper output... but somehow if your user is not present it will check like for nil and generates that error, to avoid that you have to write the condition or rescue nil on that line...

Upvotes: 0

Related Questions