如何在 Rails3 中执行搜索?

发布于 2024-10-10 05:13:13 字数 445 浏览 4 评论 0原文

我知道我可以通过在模型上调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情场扛把子 2024-10-17 05:13:13

.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.

九公里浅绿 2024-10-17 05:13:13

考虑到这里确实没有太多的关系来链接,看起来一个带有三元运算符的简单单行代码可能会这样做:

@posts = params[:title].present? ? Post.where(:title => params[:title]) : Post.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:

@posts = params[:title].present? ? Post.where(:title => params[:title]) : Post.all

... because when there is no :where clause scope, you couldn't later chain it to :all, anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文