简体   繁体   中英

Rails search form with multiple params

I am working on a search form which should accept multiple params. But it currently accepts only one.

My Controller action:

def index
  @halls = Hall.order(:name).page(params[:page]).per(9)
  @city = City.all
  @venue_type = VenueType.all
  @event_type = EventType.all

  if !params[:city].blank?
    session[:city] = params[:city]
    city = City.find_by(name: params[:city])
    @halls = @halls.where(:city => city)
  end

  if !params[:venue_types].blank?
    session[:venue_types] = params[:venue_types]
    venue_types = VenueType.find_by(name: params[:venue_types])
    @halls = @halls.where(:venue_types => venue_types)
  end

 if !params[:event_types].blank?
    session[:event_types] = params[:event_types]
    event_types = VenueType.find_by(name: params[:event_types])
    @halls = @halls.where(:event_types => event_types)
  end

end

My view:

<div class="search">
  <%= form_tag(halls_path, :method => "get", class: "navbar-form", id: "search-form") do %>

<%= select_tag "city", options_from_collection_for_select(City.all, "name", "name") %>

          <ul>
            <% @venue_type.each do |venue| %>
                <li>
                  <%= check_box_tag 'venue_type[]', venue.name -%>
                  <%=  venue.name -%>
                </li>
            <% end %>
        </ul>

        <ul>
            <% @event_type.each do |event| %>
                <li>
                  <%= check_box_tag 'event_type[]', event.name -%>
                  <%=  event.name -%>
                </li>
            <% end %>
        </ul>

      <button class="btn" type="submit">Search</button>
<% end %>
</div>

I bet the mistake is in the controller but as a newbie I can't find it. Would be grateful for the answers.

Your view defined the check_box_tag with:

<%= check_box_tag 'venue_type[]', venue.name -%>
<%=  venue.name -%>

<%= check_box_tag 'event_type[]', event.name -%>
<%=  event.name -%>

As you see, your controller must get :value_type & :event_type from params instead of :value_types & :event_types . So you can change from either view or controller, it should work, but I recommend change from view like this:

<%= check_box_tag 'venue_types[]', venue.name -%>
<%=  venue.name -%>

<%= check_box_tag 'event_types[]', event.name -%>
<%=  event.name -%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM