Rails best practice to check an object’s existence 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 ActiveRecord::Base

def has_tag !self.tags.empty? end

def get_first_tag self.tags[0] end Tags is also inherited from ActiveRecord::Base and Post 'has_many' Tags

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   name end

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.

<% if post.has_tag != nil %>

...

def has_tag !self.tags.empty? end

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".

-Dave