rails 带有可选字段的搜索表单

rails search form with optional fields

我正在尝试制作一个包含可选字段的搜索表单,以便用户可以通过参数组合进行搜索。我认为问题在于正在传递空白文本字段值,但无论如何,我的搜索都不起作用。

我在 app/models/guideline.rb:

中定义范围
scope :investor, -> (investor) { where investor: investor }
scope :program, -> (program_code) { where program_code: program_code }
scope :client, -> (client_ID) { where client_ID: client_ID }

在控制器中,我根据表单输入重新定义了@guidelines:

def index
  @guidelines = Guideline
  @guidelines = Guideline.program(params[:program_code]) if params[:program_code]
  @guidelines = Guideline.investor(params[:investor]) if params[:investor]
  @guidelines = Guideline.all
end

在视图中,我有这个简单的搜索表单:

<%= form_tag guidelines_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :investor, params[:investor], :placeholder => "Enter Investor" %>
    <%= text_field_tag :client_ID, params[:client_ID], :placeholder => "Enter Client"%>
    <%= text_field_tag :program_code, params[:program_code], :placeholder => "Enter Program:" %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

最终我想搜索表单输入的组合,但我什至无法进行简单的搜索。我很感激你们能给我的任何帮助。谢谢!!

这样试试:

def index
  # All records by default
  @guidelines = Guideline.where(1)
  # Add `program` scope if a value is given
  @guidelines = @guidelines.program(params[:program_code]) unless params[:program_code].blank?
  # Add `investor` scope if a value is given
  @guidelines = @guidelines.investor(params[:investor]) unless params[:investor].blank?
end

注意每个作用域都使用了一个unless something.blank?条件,不包括参数为空字符串的情况