Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 272
superluminary Avatar asked Jan 25 '13 16:01

superluminary


2 Answers

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.

like image 141
tadman Avatar answered Nov 04 '22 23:11

tadman


t = "%#{term}%"
where('name || email || postcode like ?', t)
like image 28
veritas1 Avatar answered Nov 05 '22 00:11

veritas1