如何在 Rails3 中执行搜索?
我知道我可以通过在模型上调用 where()
来搜索查询,如下所示: Post.where(:title => 'My First Post')
但是,如果我不知道用户是否想要过滤掉搜索参数怎么办? 例如,我有一个搜索表单,其中有一个可选的 title
字段。如果标题已填写,则表单应搜索标题。但是,如果不是,表单应该只返回所有字段。
我尝试做一些事情,但是
search = Post.all
if params[:title].present?
search.where(:title => params[:title])
end
,当我调用 Post.all 时,Rails 立即返回搜索结果,并且我无法进一步添加条件/
我该怎么做?
谢谢!
I'm aware that I can search queries by calling where()
on a model as follows:Post.where(:title => 'My First Post')
However, what if I don't know if the user wants to filter out the search parameters?
For example, I have a search form that has an optional title
field. If the title is filled, the form should search for a title. If it is not, however, the form should just return all fields.
I tried doing something along the lines of
search = Post.all
if params[:title].present?
search.where(:title => params[:title])
end
However, Rails immidiately returns the result of the search when I call Post.all and I cannot further add conditions/
How do I do this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.all
是 arel 的“完成器”方法,并导致实际调用查询(.each
和.first
也是如此)。因此,如果您希望能够有条件地继续构建范围,如果您想调用它,则.all
应该是最后调用的。.all
is a 'finisher' method for arel and causes the query to actually be called (same goes for.each
and.first
). So, if you want to be able to keep building up the scope conditionally,.all
should be the last thing called, if you want to call it at all.考虑到这里确实没有太多的关系来链接,看起来一个带有三元运算符的简单单行代码可能会这样做:
...因为当没有 :where 子句范围时,你不能无论如何,稍后将其链接到:all。
Given that there really isn't much in the way of relations to chain here, it would seem that a simple one-liner with a ternary operator might do:
... because when there is no :where clause scope, you couldn't later chain it to :all, anyway.