Rails best practice to check an object’s e xistence before displaying an attribute in a layout

I have the following code in a layout:

Posted <%=time_ago_in_words post.created_at %> ago
<% if post.has_tag != nil %>
in the <%= post.get_first_tag.name %> category
<% end %>
And the following code in the post model which is inheriting form

def has_tag

def get_first_tag
Tags is also inherited from ActiveRecord::Base and Post ‘has_many’

Firstly: Is this the best way of checking if the post object has at
least 1 associate tag attribute.

Secondly: Should I be putting this logic into a helper method?

Thirdly: Why doesn’t the following work (it returns a # where the tags
should be):

in the <%= post.tags.to_sentence %> category,
I guess its because tags aren’t actually stored as an array attribute,
but i don’t really know.

ActiveRecord already has helper methods defined, so adding wrappers
like has_tag and get_first_tag is usually not necessary, and only
makes your code more complex.

  1. You can do
    <% if post.tags.any? %>
    in the <%= post.tags.first.name %> category
    <% end %>
    And remove the get_first_tag and tags methods from your model.

  2. This kind of logic is well suited for the view layer (i think).

  3. Hard to tell without knowing what tags actually returns. Try using
    post.tags.inspect to see what it returns.
    I suspect you see ‘#’ because the objects in the array returned by
    tags doesn’t have a to_s method defined.
    to_sentence converts an array to a string using to_s on each element.

If you have a Tag class, try adding this to that class:
def to_s

If you’re using a plugin/gem for the tags, you can either monkepatch
it or do something like this:
post.tags.map(&:name).to_sentence (assuming Tag has a name attribute
you want to display).
This kind of logic is appropriate to put in a helper.


On Mon, Aug 9, 2010 at 19:23, wtb [email protected]

<% if post.has_tag != nil %>

def has_tag

false is not the same as nil. You’ve been hacking too much LISP. :slight_smile:
Dump the “!= nil”, leaving simply “if post.has_tag”.


Specialization is for insects. -RAH | Have Pun, Will Babble! -me
Programming Blog: http://codosaur.us | Work: http://davearonson.com
Leadership Blog: http://dare2xl.com | Play: http://davearonson.net