Retrieving records using like condition

So I’ve got a model called Item and one of its properties is called
“tags”. It’s just string that is a simple comma separated list of tags
associated with the item. I’m trying to do two things. First create a
list of items with the most common tags (the top ten or so) and second
allow the user to click on a link that will show all the items with the
selected tag.

My problem is actually with the second task. Retrieving records that
contain the tag “dog” for example is pretty simple, however I ran into a
problem when I needed to retrieve records with the tag “not a dog”.
Whenever I search for records with the tag “dog” it also returns the
records with the tag “not a dog” because “dog” is in “not a dog”.

It took me a while but I got something that does what I want it to do,
but I’m just not convinced it’s the best way to go about doing things.
Here’s what I got:

@items = Item.find(:all, :conditions => [‘tags LIKE ? and folder_id =
?’, ‘%’ + params[:tag] + ‘%’, @folder.id])

@items.delete_if { |item|
tags = item.tags.split(’,’)

delete = true

for tag in tags
tag.downcase!
tag.strip!

if tag == params[:tag]
  delete = false


end

end

delete
}

Whenever params[:tag] is “dog” this succeeds in only picking out the
items that contain the tag “dog” but not ones that contain similar tags
such as “not a dog”. But like I said it just seems icky and not
cumbersome.

Is there some way to make the find command, or the SQL syntax for like
handle searching through comma separated lists?

On 7 April 2010 08:57, Sean E. [email protected] wrote:

So I’ve got a model called Item and one of its properties is called
“tags”. It’s just string that is a simple comma separated list of tags
associated with the item. I’m trying to do two things. First create a
list of items with the most common tags (the top ten or so) and second
allow the user to click on a link that will show all the items with the
selected tag.

Stop and refactor that into a “has_many :tags”/“belongs_to :item”
association.
Your life will be much easier.