DEV Community

Shivashankar
Shivashankar

Posted on

Using Splat (*) operator in Active record Query

Introduction

In Rails often we use active record to build custom search queries.

This post is about how to use splat(*) operator with active record

Assume we have a table employees with following fields

  1. first_name
  2. middle_name
  3. last_name
  4. email

and we have a class method list to filter the employees

class Employee < ApplicationRecord
  def self.list(search_key='')
    arel = order("first_name")

    if search_key.present?
      search_term = "%" + search_key + "%"
      arel = arel.where("first_name LIKE ? OR middle_name LIKE ? OR last_name LIKE ? OR email LIKE ?", 
                         search_term, search_term, search_term, search_term)
    end
   arel 
  end 
end

The code can be bit optimised using Splat operator as follows

class Employee < ApplicationRecord
  def self.list(search_key='')
    arel = order("first_name")

    if search_key.present?
      search_term = Array.new(4){ "%" + search_key + "%" }
      arel = arel.where("first_name LIKE ? OR middle_name LIKE ? OR last_name LIKE ? OR email LIKE ?", *search_term)
    end
   arel 
  end 
end

In above case all fields are strings

Case 2 : How about searching fields with different data types

Assume we now have a table employees with following fields

  1. first_name
  2. middle_name
  3. last_name
  4. email
  5. age (integer)
  6. mobile: integer ( for example case)

In this case the query will be

class Employee < ApplicationRecord
  def self.list(search_key='')
    arel = order("first_name")

    if search_key.present?
      search_term_str = Array.new(4){ "%" + search_key + "%" }
      search_term_int = Array.new(2){ search_key }

      arel = arel.where("first_name LIKE ? OR middle_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR age = ? OR mobile = ?", 
                        *search_term_str, *search_term_int)
    end
   arel 
  end 
end

We shall create multiple splat groups based on the data type as above to optimize the code

Latest comments (0)