Am Dienstag, den 07.03.2006, 11:59 +0100 schrieb Alexander MacCaw:
I’m trying to create a search where I can find pages by their tag name.
Here’s a sample of my code (not working).
@tags = Page.find(:all, :conditions => [“#{:tag.name} LIKE ?”,‘%’ +
@params[‘searchtags’] + ‘%’ ])
Why is your instance variable call @tags, if you are looking for pages?
My enviroment:
I’ve got a table called tags, and a table called pages, both with a
relationship of has_and_belongs_to_many. I also have a table called
pages_tags. Basically my tables are set up like here:
http://www.railsdiary.com/diary/tagging_has_and_belongs_to_many
Would appreciate some help on how I can reference a tag through a Page.
You post is a little confusing, but i guess you want to do the
following:
@pages = Page.find(
:all,
:include => :tags,
:conditions => [‘tags.name LIKE ?’, “%#{params[:searchtags]}%”]
)
This will work, if you have a search string like ‘boat’ or ‘strawber’,
just a single tag, partial or complete.
If you have multiple tags in your search string, you should separate
them before querying:
will split on whitespaces
tags = params[:searchtags].split(/\s/)
@pages = Page.find(
:all,
:include => :tags,
:conditions => [‘tags.name IN (?)’, tags.join(‘,’)]
)
This will only work for complete tags.
Norman T.
http://blog.inlet-media.de