How to use the search in acts as taggable

694 views Asked by At

I am using acts-as-taggable-on gem.

i want to use search both name as well as tags in single search field

my model

class User < ActiveRecord::Base

  acts_as_taggable
  attr_accessor: :name, :age, :country, tag_list

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

Controller

class UserAppsController < ApplicationController

  def index
    @users = User.search(params[:search])
    //@users = User.tagged_with(params[:search])
  end
end

Help me to solve this.

1

There are 1 answers

4
Ziv Galili On

One way is to add both results one to another using + :

@users = User.search(params[:search])
@users = @users + User.tagged_with(params[:search])

A better solution will be to change your search method in the model to return the full result:

where('name LIKE ?', "%#{search}%") + tagged_with(search)

but if you want to split the name search from the tag search, you can split them into scopes or something like that and then use it:

scope :name_contains, -> (query) { where('name LIKE ?', "%#{query}%") }

and in your search method:

name_contains(search) + tagged_with(search)

btw if you want the name search to be case insensitive use something like:

scope :name_contains, -> (query) { where("REPLACE (lower(name), ' ', '' ) like ?", "%#{query.downcase}%") }