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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With