Forum: Ruby on Rails has_and_belongs_to_many tags

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Baf018e2cc4616e4776d323215c7136c?d=identicon&s=25 Alexander MacCaw (Guest)
on 2006-03-07 11:59
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'] + '%' ])


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

Would appreciate some help on how I can reference a tag through a Page.
Bf66e10c8fc4abefebde0425e7f6f15a?d=identicon&s=25 Norman Timmler (Guest)
on 2006-03-07 18:01
(Received via mailing list)
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_be...
>
> 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 Timmler

http://blog.inlet-media.de
This topic is locked and can not be replied to.