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?

Answers


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' %>

Need Your Help

Master detail grid in Silverlight 4 - No headers for Detail grid

c# silverlight datagrid silverlight-4.0 master-detail

I'm developing a Silverlight application where I want the master and its detail grid to share the same columns.

Error while converting query from mysql to oracle

mysql oracle postgresql oracle10g

I have four queries in mysql in my webapp that I am trying to convert into oracle queries. However, the datetime string breaks when I try to run the new query. Can someone help me figure out what I...