1

In a custom advanced search form, what is the best way to perform a query to filter results?

class UsersController < ApplicationController

  def index
    @users = User.all
  end

end

In many case we have different types of data, for example:

name will be a string, surname will be a string, age will be an integer

In my specific case, i have a form with some filters that user can or can not fill. How can i do a dynamic query?

Mattia M.
  • 464
  • 1
  • 4
  • 16

2 Answers2

0

Try this

User.where("name = ? or surname = ? or age = ? ", params[:first_name], params[:lastname], params[:age])
Sachin R
  • 11,606
  • 10
  • 35
  • 40
0

In you controller do this:

class UsersController < ApplicationController

  def index
    @users = User.search params[:filter]
  end

end

Then in User model do:

class User < ActiveRecord::Base
  def self.search(options = {})
    users = User.all
    users = users.where(name: options[:name] ) if options[:name].present?
    users = users.where(first_name: options[:first_name] ) if options[:first_name].present?
    users = users.where(last_name: options[:last_name] ) if options[:last_name].present?
    users = users.where(age: options[:age] ) if options[:age].present?
    users
  end
end
usmanali
  • 2,028
  • 2
  • 27
  • 38