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

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -