I have a State model which has_many :cities and a city model which belongs_to :state.
I want to show a list of States, then when a user clicks on a State make an ajax call to show the cities belonging to that state below.
I’m sure this can be done using jQuery and without partials, I’m just having trouble coming up with some examples & solutions.
Here’s what I want it to look like first:
– Alabama
– Alaska
– Arkansas
– etc..
Then if someone clicks on ‘Alaska’ the list would update to:
– Alabama
– Alaska
– Anchorage
– Fairbanks
– Juneau
– Arkansas
Any help would be much appreciated!
EDIT
Ok, so I’ve been expelling jQuery I’ve come up with the following code. I can’t get the states to individually show their respective cities. As is, if you click on any of the states, it only shows the cities for the first one.
Here’s the code:
<script>
$(function(){
$('#city').hide();
$('.toggle').toggle(function(){
$('#city').fadeIn(100);
},
function(){
$('#city').fadeOut(100);
});
});
</script>
<%= render "layouts/header"%>
<table class="state_list">
<% @states.in_groups_of(1, false).each do |state| %>
<tr>
<% for state in state %>
<td>
<div class="toggle"><h3><%= state.name %><br /></h3></div>
<% @cities.each do |city| %>
<% if city.state.id == state.id %>
<div id="city"><%= link_to city.name, cities_path(:city_id => city.id) %> (<%= city.posts.where(:published => true).count %>)<br />
<% end %>
<% end %>
</div>
</td>
<% end %>
</tr>
<% end %>
</table>
Again, I appreciate any feedback!
StackOverflow Answer
I GOT IT!
Here’s what I did for reference… Also, if you see a better method, please let me know.
Everything is working just like I hoped!