Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter results on index page from dropdown

I'm using rails 3 and I have two models, venues and areas where each area has many venues and each venue belongs to one area.

I'm trying to find a way of filtering the venue records displayed in the venue index by what area is selected in a dropdown box on the same page.

The dropdown box currently displays all my area records as I would like but after selecting an area and clicking the submit button I would like the index page to reload and only display the partials of the venue records with the same area as the one selected in the dropdown box.

The scopes I have in the model display the correct venues when called in the rails console or by changing the def index in the controller to @venues = Venue.north / venue.south / venue.west. I just cant figure a way to have all the venues displayed as a default but to then call each scope depending on which area is selected from the form.

I'm not bothered with using AJAX at this point I would just like to understand how it can be done in as simple a way as possible and without using sphinx/thinking_sphinx.

Model:

class Venue < ActiveRecord::Base
  belongs_to :user
  has_many :reviews
  belongs_to :area

  scope :north, where(:area_id => "2")
  scope :west, where(:area_id => "3")
  scope :south, where(:area_id => "4")
end

View: (venue index.html.erb)

<div class="filter_options_container">

  <form class="filter_form">
    <%= select("area", "area_id", Area.all.map {|a| [a.name, a.id] }) %>
    <input type="submit" value="Filter" />
  </form>
</div>

<div class="venue_partials_container">
  <%= render :partial => 'venue', :collection => @venues %>
</div>   

Controller:

class VenuesController < ApplicationController

  def index
    @venues = Venue.all
  end
end

Any help is much appreciated.

like image 663
Dave Avatar asked Jan 30 '11 23:01

Dave


1 Answers

You can find the Venues in your controller depending on whether an area is selected or not. You can modify the view to send the area name, instead of the area id(which might make it easier):


<%= select("area", "name", Area.all.collect(&:name)) %>

The controller would look something like this -


def index
  if (params[:area] && Area.all.collect(&:name).include?(params[:area][:name]))
     @venues = Venue.send(params[:area][:name].downcase)
  else
     @venues = Venue.all
  end
end

like image 184
Punit Rathore Avatar answered Sep 18 '22 16:09

Punit Rathore