Simple search using attribute, and act_as_taggable

I am creating an application in which I would like to use a simple search to search by the name of the object, and the tags (using act_as_taggable_on) in one search

I can build either, but not both, and I'm finally trying to figure it out.

To search using tags, I use:

@post = Post.tagged_with(params[:search]) 

To search for an object, I use:

 @post = Post.search(params[:search]) 

And I wrote a method called search in the Post model as follows:

 def self.search(search) if search where('question LIKE ?', "%#{search}%") else scoped end end 

Any idea how to combine these two queries? Any attempts have so far failed, mainly because my Post model does not have a “tag” column, etc.

+4
source share
3 answers

I understood this and tested it in my decision, I wrote my associations myself, so it is not as clean as I would like, if someone has a better solution, I will still see it. Here is what I came up with:

 q = "%#{search}%" Post.select('distinct posts.*').joins("LEFT JOIN taggings on posts.id = taggings.taggable_id") .joins("LEFT JOIN tags on tags.id = taggings.tag_id") .where('title LIKE ? OR tags.name LIKE ?', q, q ) 

This works as expected in my tests. I am testing three records. One has a search term in the title, the other has only a tag, and the third has both a title and a tag, so it should not return duplicates.

Hope this helps.

+2
source

I found this: Search form with act_as_taggable_on (Rails 3)

this might work, but I also push my results with the kaminari stone, so when I use this approach, I get the following error:

 undefined method `page' for []:Array 

So this will not work in my situation. I would like to find a single request solution to handle all of this.

+1
source

As a continuation of Andrew’s code, I used this search method in my model - simply adding case insensitivity and making the “title” query more explicit, since my model did contain a “name” attribute that was ambiguous.

 def self.search(search) if search.present? q = "%#{search}%" Post.select('distinct posts.*').joins("LEFT JOIN taggings on posts.id = taggings.taggable_id") .joins("LEFT JOIN tags on tags.id = taggings.tag_id") .where('lower(posts.title) LIKE lower(?) OR lower(tags.name) LIKE lower(?)', q, q ) else all end end 
0
source

Source: https://habr.com/ru/post/1396024/


All Articles