views:

40

answers:

3

I tried note.tags.nil?, but it didn't work. How do I do this? Thanks for reading.

+2  A: 

If you want to know if a @note has any associated tags, you can use

@note.tags.empty?
j.
A: 

In Addition, you could think about having a counter cache column for Tags. With that :tags_count you wouldn't need another SQL query. You could check then with @note.tags_count == 0, @note.tags_count.zero? or whatever you like.

tbuehlmann
A: 

You can call @note.tags.any? to test if there are any tags. Note that this will hit the database to do a count. You might want to left join when pulling out @note, to save this query. Eg.:

Note.first(:select => 'notes.*, case when tags.id is not null then 1 else 0 end as has_any_tags', :joins => "LEFT JOIN tags ON tags.note_id = notes.id")

Your Note model will now have a field has_any_tags that is either 0 (false) or 1 (true), if there are any related tags.

You can move the query options above into a default scope and wrap the field up in an accessor:

class Note
  has_many :tags
  default_scope :select => 'notes.*, case when tags.id is not null then 1 else 0 end as has_any_tags', :joins => "LEFT JOIN tags ON tags.note_id = notes.id"
  def has_any_tags?
    has_any_tags == "1"
  end
end

Now, it all happens transparently:

>> Note.first.has_any_tags?
=> true
troelskn