Rails: Display user name, if user not exist, display 'Anonymous' Instead
I write:<%= @blog.user.name || 'Anonymous' %>
But when @blog.user is nil, it will report undefined method name for nil:NilClass How to get around this and display Anonymous Instead?
This is perfect case to use ActiveSupport's Object#try method:
<%= @blog.user.try(:name) || 'Anonymous' %>
This way you call name method on @blog.user only if it responds to this method (which isn't true if it's nil).
I would do this using the ? operator
<%= @blog.user ? @blog.user.name : 'Anonymous' %>