views:

47

answers:

2

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.


+1  A: 

For one thing, you probably need

<% if post.has_tag %>

instead of

<% if post.has_tag != nil %>

In your definition, has_tag should never return nil, and thus 'in the...' part will always be shown.

Generally, your idea seems fine to me: I often add helpers like these to models.

Nikita Rybak
Ahh, typo by me I was modifying the code while writing the question and forgot to update, thanks for reply
wtb
+3  A: 

This is a perfectly good way of checking if there are tags or not. However, self.tags.empty? will return true or false so post.has_tag will never be nil.

It's worth noting that, in ruby, it is common to name methods that return true or false with a question mark. So post.has_tag? would be a better name for your method (like the empty? method for the tags).

This sort of method belongs in the model class rather than a helper as it is not specific to the view layer; you might want to call this method from other model classes, for example.

The reason you are getting # instead of your tag names is that you are trying to convert a collection of tags to a sentence and you need instead to convert the names of the tags to a sentence. You should be able to do

post.tags.map(&:name).to_sentence

which will take the names of the tags and turn them into a sentence.

Shadwell
thanks for the response, 3 really useful pointers in here
wtb
Yes, definitely make the function name end in ? for any function that returns a boolean.
Jason Noble