DEV Community

Shivashankar
Shivashankar

Posted on

2 2

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay