按带 * 通配符的条件查找
我有一个带有两个参数的搜索表单。如果参数为空,我想搜索全部。
var_1 = params[:var_1].blank? ? "*" : params[:var_1]
var_2 = params[:var_2].blank? ? "*" : params[:var_2]
@mymodels = MyModel.find(:all,:conditions=>["var_1 = ? and var_2 = ?",var_1,var_2])
这就是我得到的:
SELECT ... WHERE (var_1 = '*' and ...
我需要的是:
SELECT ... WHERE (var_1 = * and ...
有什么建议吗?
I have a search form with two params. If a param is empty I'd like to search all.
var_1 = params[:var_1].blank? ? "*" : params[:var_1]
var_2 = params[:var_2].blank? ? "*" : params[:var_2]
@mymodels = MyModel.find(:all,:conditions=>["var_1 = ? and var_2 = ?",var_1,var_2])
This is what I got:
SELECT ... WHERE (var_1 = '*' and ...
what I need is:
SELECT ... WHERE (var_1 = * and ...
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会有条件地建立标准清单。即如果相应参数不为空,则仅在查询中包含一个字段:
然后运行
find
:I would build up the list of criteria conditionally. i.e. only include a field in the query if the corresponding parameter is not blank:
and then run the
find
:我会考虑建立一个可修改的查询,因为 arel 是建立在这个想法之上的。
例如,
我在这里使用 Model::scoped 以便能够继续我的搜索,因为它
返回一个 ActiveRecord::Relation 对象,而不是像 Model.all 这样的数组
会。
我发现开始广泛搜索然后缩小范围很有帮助。
希望它有帮助,
-卢克
I would look into building up a modifiable query, as arel is built upon this idea.
For example,
I used Model::scoped here to be able to continue my searches, because it
returns an ActiveRecord::Relation object, and not an array like Model.all
would.
I've found it helpful to start broad searches and then narrow them down.
Hope it helps,
-Luke
我想
SELECT ... WHERE (var_1 = * and ...
无论如何都行不通,因为你需要的是一个 like 子句,例如:
SELECT ... WHERE var_1 like '%' 和 ...
所以一个选择应该是,有一个单独的方法:
例如:
IMO,有时最好编写更多代码,以便逻辑可以轻松管理。
I guess having
SELECT ... WHERE (var_1 = * and ...
will not work anyway, as what you need there is a like clause,Ex:
SELECT ... WHERE var_1 like '%' and ...
So one option should be, have a separate method:
Ex:
IMO, sometimes it better to write more code, so that the logic can manage easily.