Aarthi
Aarthi

Reputation: 1521

Search field in rails 5

I have an index page with users list where I want to implement a search field, and filtering records based on the text field of users

scope :filter_users ->(params[:search]) { where("name like %#{params[:search]}%)

where i also need to check the the associated object name. I.e user belongs to organization, I need to add condition at scope to check the organisation name.

Upvotes: 0

Views: 137

Answers (1)

Péha
Péha

Reputation: 2933

Your question was missing this, but I'll suppose your model is something like:

class User
  belongs_to :organization
end

class Organization
  has_many :users
end

To setup a search on the relation, you'll first need to join to the organization table onto users and search on the result of the join, filtering both on the user name and the organization name. It would look something like:

class User
  belongs_to :organization

  # I took the liberty of fixing your simple search syntax
  scope :simple_search,  ->(query) { where('name like ?', "%#{query}%") }
  # The complex search:
  # 1. Inner joins users table to organizations table
  # 2. Applies a where conditions to the result of the join (note: we need to
  # specify the table name in the where because both models have a name field)
  scope :complex_search, ->(query) { joins(:organization).where('users.name LIKE :q OR organizations.name LIKE :q', query:"%#{query}%")}
end

And used like this:

# returns only users whose name matches '%ben%'
User.simple_search('ben')  
# returns users whose name matches '%ben%' and users belonging to
# companies whose name matches '%ben%'
User.complex_search('ben')

You can find an example of this (and interesting details about things I used in my answer, and lots of other things as well) in the official Active Record Query Interface guide, and for this particular matter, in the specifying conditions on the joined tables section.

Upvotes: 1

Related Questions