Topic: Nil Error when no review is present

I'm working on an application that has the models:

Album has_one :review
Review belongs_to :album

In my views i would have something like this:
<%=link_to album.title...etc%><br>
<%=album.review.body%>

That works if a review is in the database, but If no review body is in the database, I get an error along with an unrendered page.
Is there a way to prevent rails from doing this?

Re: Nil Error when no review is present

there's probably a much nicer way, but I normally just slap an if/unless conditional in..

<%= album.review.body unless album.review.body.nil? %>

I'd be interested to hear if there is a better/cleaner/dry-er way, which I've no doubt there is.

Last edited by idlefingers (2006-11-19 08:25:30)

Re: Nil Error when no review is present

Thanks. This works for now.
smile

Re: Nil Error when no review is present

Also, if there is more information than just the body that you want to show, you can just do:

<% unless album.review.nil? -%>
  <%= album.review.author %>
  <%= album.review.body %>
  etc...
<% end -%>

That is assuming you require all the fields that you are trying to display..
cheers.

Re: Nil Error when no review is present

Well, only slightly better is one that I use:

<%= album.review.body || '' %>

Re: Nil Error when no review is present

this is great, guys.
Thanks a ton.