刚开始使用 Ransack,我很喜欢它。但非常想知道如何从空白索引开始却没有结果?强制用户使用搜索表单。这是到目前为止控制器的样子。
meals_controller.rb
def index
@search = Meal.search(params[:q])
@meals = @search.result
end
编辑 -
有些是如何运作的,但我不确定如何
meals_controller.rb
class MealsController < ApplicationController
before_filter :set_search
def index
if params[:q].blank?
@q = Meal.none.search
else
@q = Meal.search params[:q]
end
@meals = @q.result
end
def set_search
@search=Meal.search(params[:q])
end
end
我不喜欢使用空白范围,因为您进行不必要的查询。
我使用以下方法:
# If no search params, default to empty search
if params[:q] && params[:q].reject { |k, v| v.blank? }.present?
@q = User.search(params[:q])
@users = @q.result
else
@q = User.search
@users = []
end
然后您仍然可以在视图中为您的
search_form_for
使用@q,但默认情况下不会进行查询。
更新:
正如@Petercopter 指出的:
从 Rails 4 开始,有一个原生作用域
none
甚至不触及数据库。它返回一个空的 ActiveRecord::Relation
。
旧答案:
我使用名为
none
的假范围,它不会返回像 where('1=0')
这样的记录。def index
if params[:q].blank?
@q = Meal.none.search # so you have a ransack search
else
@q = Meal.search params[:q]
end
@meals = @q.result
end
补充:
您认为您需要:
<%= search_form_for @q, url: meals_path, html: {method: :get} do %>
...
<% end %>