Rails: Display user name, if user not exist, display 'Anonymous' Instead -
i write:<%= @blog.user.name || 'anonymous' %>
but when @blog.user nil, report undefined method name nil:nilclass how around , display anonymous instead?
this perfect case use activesupport's object#try method:
<%= @blog.user.try(:name) || 'anonymous' %> this way call name method on @blog.user if responds method (which isn't true if it's nil).
Comments
Post a Comment