Ransack搜索包括参数

时间:2016-03-02 15:06:45

标签: ruby-on-rails ransack

我正在使用gem'ransack'搜索记录。

我正在编程的页面只有一个下拉菜单才能选择@department。 之后,我希望Ransack在@department内搜索。

我需要在Ransack搜索参数中包含一个额外的参数department=2。 (如果我将其插入浏览器URL,则有效。)

输入department = 2后的

浏览器URL

http://localhost:5000/departments/costfuture?department=2&utf8=%E2%9C%93&q%5Bid_eq%5D=&q%5Bproject_year_eq%5D=&q%5Boriginal_year_eq%5D=&q%5Bclient_id_eq%5D=43&q%5Blocation_name_cont%5D=&q%5Bproject_name_cont%5D=&q%5Bcoststatus_id_in%5D%5B%5D=&q%5Bcoststatus_id_not_in%5D%5B%5D=&q%5Brebudget_true%5D=0&q%5Bnew_true%5D=0&q%5Bconstruction_true%5D=0&q%5Bmaintenance_true%5D=0&commit=Search

这是控制器:

  def costfuture

    @departments = current_user.contact.departments
    if params[:department]
      @department = Department.find(params[:department])
      @search = @department.costprojects.future.search(params[:q])
      @costprojects = @search.result.order(:department_priority)
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @departments }
    end
  end

我在视图中尝试了这个:

<%= search_form_for @search, url: departments_costfuture_path(:department => @department.id) do |f| %>

但是,生成的网址缺少department=2

2 个答案:

答案 0 :(得分:1)

如果您想将department选项传递给Ransack,可以使用search_form_for中的隐藏字段执行此操作:

<%= search_form_for @search, url: departments_costfuture_path do |f| %>
  <%= f.hidden_field :department_eq, value: @department.id %>
  <%# Other form code here %>
<% end %>

但是如果你想搜索一个特定的部门,那么最好使用Rails路由。您可以通过修改config/routes.rb生成/departments/2/costfuture之类的网址:

resources :departments do
  get 'costfutures', on: :member
end

现在,您可以使用生成的URL帮助程序生成将设置params[:id]的链接,您可以使用它来检索@department

答案 1 :(得分:0)

我最终在 hidden_field_tag 中使用了 search_form_for

<%= search_form_for @search, url: departments_costfuture_path do |f| %>
  <%= hidden_field_tag :department, @department.id %>
  <%= f.search_field :last_name_or_first_name_cont %>
<% end %>

然后可以在控制器中访问 params[:department]params[:search]