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

荒凉一梦 提交于 2021-01-26 19:23:52

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/14526389/is-there-a-dry-way-to-pass-bind-variables-to-an-ar-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!