14

I have code like this:

t = "%#{term}%"
where('name like ? or email like ? or postcode like ?', t, t, t)

As you can see it's performing a search across several fields.

Is there a way to avoid the duplicated t? It's making me feel dirty.

Thanks

superluminary
  • 47,086
  • 25
  • 151
  • 148

2 Answers2

29

You can do it with a named placeholder:

where('name LIKE :name OR email LIKE :name OR postcode LIKE :name', :name => t)

This is often the best way to repeat a singular value several times in a query.

tadman
  • 208,517
  • 23
  • 234
  • 262
1
t = "%#{term}%"
where('name || email || postcode like ?', t)
veritas1
  • 8,740
  • 6
  • 27
  • 37