I've run into a small problem with some search-functionality for a Rails 3 website I'm developing. I have a simple Post
model that looks like this:
class Post < ActiveRecord::Base
acts_as_taggable
end
I'm using acts_as_taggable_on
to make adding tags to my posts a bit easier. When I have a post tagged 'rails' and I do the following, all works well:
@posts = Post.tagged_with("rails")
Thing is, I also want to search for the title of the post. When I have a post titled 'Hello world' and tagged 'rails', I want to be able to find this post by searching for 'hello' or 'rails'. So I want a LIKE
statement for the title column in combination with the tagged_with
method acts_as_taggable_on
provides. The where
scope doesn't work, because it uses AND
instead of OR
.
I hoped meta_search
would fix the problem, but this isn't working for me. I tried several things. Here are two examples of what I tried:
@search = Post.search(:tagged_with_or_title_like => params[:search])
@search = Post.search(:title_like => params[:search], :tagged_with => params[:search])
It just doesn't recognize 'tagged_with'. It's my first time using meta_search
, so I might be doing something wrong here. ;) I've read somewhere that searchlogic
worked in combination with acts_as_taggable_on
, but since it doesn't support Rails 3, I can't use that.
I hoped somebody here could help me with this problem. Anyone know how to combine acts_as_taggable_on
with meta_search
? Or maybe know a solution without meta_search
? Also, if there's a better option for acts_as_taggable_on
that works with meta_search
I'd love to hear that too. :)
EDIT:
I got it working without using tagged_with
or meta_search
. It looked like this:
Post.select("DISTINCT posts.*").joins(:base_tags).where("posts.title LIKE ? OR tags.name = ?", "%"+params[:search]+"%", params[:search])
The query created was ridiculous, so I tried a different route: without acts_as_taggable_on
and meta_search
. I created a tags table myself and connected it to the posts with has_and_belongs_to_many
. I won't have other tables that need to be connected to the tags, so this will do the trick for me. I created a scope for searching both the tags and title:
scope :search, lambda { |search| select("DISTINCT posts.*").joins(:tags).where("posts.title LIKE ? OR tags.name = ?", "%"+search+"%", search) }
Now I can do the following:
Post.search(params[:search])
It works great and the query is also quite nice. Still, if anyone knows a better way: please tell me. It could also be helpful for the people coming here via Google.
Post.metasearch({:title_or_tag_taggings_tag_name_contains => params[:search]})
enjoy
I think the solution you're looking into is using database VIEW as new model.
You can create view containing join tables Post and Tags.
Then you can search it, using meta_search without problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With