Is there a DRY way to pass bind variables to an AR Relation?
Asked Answered
C

2

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

Crystallization answered 25/1, 2013 at 16:45 Comment(0)
E
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.

Eke answered 25/1, 2013 at 16:49 Comment(0)
D
1
t = "%#{term}%"
where('name || email || postcode like ?', t)
Daft answered 25/1, 2013 at 16:49 Comment(1)
it's syntactically correct (|| is the string concatenation operator) but it doesn't do the same thing as the original queryMellen

© 2022 - 2024 — McMap. All rights reserved.