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

时间:2015-02-02 02:48:44

标签: html ruby-on-rails ruby forms ruby-on-rails-4

我正在尝试使用可选字段创建搜索表单,以便用户可以通过参数组合进行搜索。我认为问题在于传递空白文本字段值,但无论如何,我的搜索都无效。

我在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 %>

最终我想要搜索表单输入的组合,但我甚至无法让简单的搜索工作。我很感激你们给我的任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

试试这样:

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?条件,这排除了参数为空字符串时的情况