Get the value of has_many in rails error(no method error)-Collection of common programming errors
The problem is that at least one of the comments
on your post
object has a nil
value for the user
association. You’re checking that email
is not nil, but you’re not checking whether user
itself is nil (which is what is triggering the NoMethodError
).
As a start, I would change this line:
to:
This is a handy pattern in ruby which first checks that comment.user
is defined, and if it is defined returns the second argument, i.e. comment.user.email
. If comment.user
is not defined (or nil
, or false
) then the second argument is not evaluated, and the return value is nil (so if no user is defined, then comment.user.email
is never evaluated so you don’t get an error).
Originally posted 2013-11-09 21:20:56.