Dan
Dan

Reputation: 1288

Multiple field comparison in Rails where clause

Is there a cleaner, DRYer, way to write this in Rails 5.0 using Postgres as the DB?

CrmRevenueLineItem.references(:crm_account)
.where("crm_accounts.name ILIKE :qry OR crm_accounts.legal_name ILIKE :qry 
        OR crm_accounts.website ILIKE :qry", qry: wildcard_query)

I feel like I'm repeating myself a lot in there. It was worse before I learned about named parameters (the :qry) and was using ? as the placeholder.

Upvotes: 1

Views: 57

Answers (1)

Lyzard Kyng
Lyzard Kyng

Reputation: 1568

A little bit shorter variant using concat_ws function

CrmRevenueLineItem.references(:crm_account)
.where("CONCAT_WS(' ', crm_accounts.name, crm_accounts.legal_name, crm_accounts.website) ILIKE :qry", qry: wildcard_query)

Upvotes: 2

Related Questions