在用户按下搜索按钮之前,如何在 meta_search 中设置 0 结果
我在 Rails 3 应用程序上使用meta_search。默认情况下(在按下搜索按钮之前)meta_search 返回搜索模型的所有元素。我想在用户按下搜索按钮之前或搜索参数为空时设置 0 结果。
我使用 meta_search 如下:
def index
@search = Article.search(params[:search])
if params[:search].blank?
@places = nil
else
@places = @search.all
end
end
如果搜索参数为空,设置 0 结果的最佳方法是什么?
谢谢
I'm using a meta_search on my rails 3 app. By default (before pressing a search button) meta_search returns all elements of searching model. and I want to set 0 result before user pressing a search button or if search params is blank.
I am using meta_search as follows:
def index
@search = Article.search(params[:search])
if params[:search].blank?
@places = nil
else
@places = @search.all
end
end
What is the best way to set a 0 result if search params is blank ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为元搜索真正提供了开箱即用的功能,但你总是可以欺骗它。
I don't think that's something that Meta Search really provides out of the box but you can always cheat it.
在我看来,你的解决方案已经足够好了。它在做什么很清楚,并且不会不必要地访问数据库。但代码可以改进为:
检查哈希值是否为空并不是解决问题的方法。类似于
{'name_contains' =>; 的哈希值''}
(如果提交的表单为空白,您将得到该结果)将返回false
。另外,最好将
@places
设置为空数组,而不是nil
。这样你就不必检查nil
并且你的循环仍然可以工作。In my opinion, your solution is good enough. It's clear about what it's doing and it doesn't access the database unnecessarily. But the code can be improved to:
Checking the hash for blank is not the way to do it. A hash like
{'name_contains' => ''}
, which is what you get if the form submitted is blank, will returnfalse
.Also it's better to set
@places
to an empty array rather thannil
. This way you don't have to check fornil
and your loop will still work.