RubyOnRails nested/dependent dropdown menu
I have a view with 3 dropdown. For example i have Country, State and City and in the view when the user select Country = US, then in the State dropdown it should populate a list of only US states, and when the state is selected the dropdown only need to bring up the Cities under that state. My Database is setup properly (State have state name and country_id field and City have city name and state_id)
I implemented the following in my view but this bring me all the records regardless of the user selection.
<div class="field">
<%= f.开发者_如何学JAVAlabel :sector, "Sector" %>
<%= f.collection_select :sector_id, Sector.all, :id, :nombre, :prompt => false %>
</div>
<div class="field">
<%= f.label :municipio %>
<%= f.collection_select :municipio_id, Municipio.all, :id, :nombre, :prompt => false %>
</div>
<div class="field">
<%= f.label :provincia %>
<%= f.collection_select :provincia_id, Provincia.all, :id, :nombre, :prompt => false %>
</div>
How can i make these dropdown dependants from each others?
Maybe one thing to try would be to add an option so that it becomes:
<%= f.label :state%>
<%= f.collection_select :country, :state_id, State.all, :id, :nombre, :prompt => false %>
</div>
<div class="field">
<%= f.label :city%>
<%= f.collection_select :state, :city_id, City.all, :id, :nombre, :prompt => false %>
</div>
The first three options in collection_select are object, method, collection. So this would be like saying, get the state ids belonging to your instance of country and return the ones that are in the collection returned by State.all.
And make sure that your models are setup appropriately:
class State < ActiveRecord::Base
belongs_to :country
end
class City < ActiveRecord::Base
belongs_to :state
end
精彩评论