搜索可能的多个参数

时间:2015-08-20 02:42:55

标签: ruby-on-rails forms search

我想要搜索可能有2个参数,但两者都不需要在场。现在,state_id传递为""如果没有选择,我也不知道如何摆脱它。

查看:

<div dropdown-toggle>
 <%= form_tag('/municipalities', method: :get) do %>
 <%= select_tag(options_for_select(@dropdown), {:allow_blank => "Please select"}, class: "btn btn-default btn-lg dropdown-toggle")  %>
  <%= submit_tag "Search", class: "btn btn-default"
 %>
  <%= link_to "Reset", municipalities_path, class: "btn btn-default" %>
  <%= button_tag 'Counties Only', name: "municipality_type", value: "County", class: "btn btn-default pull-right" %>
 <% end %>
</div>

控制器(我还是新的,所以这不是那么干净)

 def index

  @dropdown = State.all.map{ |s| [s.state, s.id]}
  @municipality = Municipality.order(:name)
  @count = @municipality.count

  if !params[:state_id].to_s.blank? && params[:municipality_type].present?
        @municipalities = Municipality.where(municipality_type: params[:municipality_type], state_id: params[:state_id])
        @forms = Form.where(municipality_id: @municipalities, state_id: @state)
        if !params[:state_id].blank?
          @present = params[:state_id] 
          @state = params[:state_id]
          @state_name = State.find(@state)
        end
        @count_state = @municipalities.count
  elsif params[:state_id].present?
    @present = params[:state_id] 
    @state = params[:state_id]
    @state_name = State.find(@state)
    @municipalities = Municipality.where(state_id: @state)
    @forms = Form.where(municipality_id: @municipalities)
    @count_state = @municipalities.count
  else
    @forms = nil
    @state = State.all
    @municipalities = Municipality.order(:name)
  end
end

2 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您可以分别简单地if params[:state_id] && params[:municipality_type]elsif params[:state_id]设置您的条件,如果在表单中提交,他们将通过该条件。

答案 1 :(得分:0)

我会开枪,我可能无法正确解释你的意图。您似乎正在定义许多您不需要的变量。

我相信这就是你需要通过两个参数搜索市政当局所需要的,但允许它们是空白的:

def index
  @municipailies = Municipality.order(:name)
  state_id = params[:state_id]
  type = params[:municipality_type]
  @municipalities = Municipality.where(state_id: state_id) if state_id
  @municipalities = Municipality.where(municipality_type: type) if type
end