Reputation: 17072
I'm working on a rails app but cannot find how to handle dependent drop down lists. I have 3 models: - Category which has several groups - Group which has several members - Member
When a category is selected, I'd like the groups within this category to populate the second drop down list (and same thing between group and member).
I have the following form (obviously this is not working how I'd like as I take all the items for the particular model)...
<div class="field">
<%= f.collection_select(:category, Category.find(:all), :id, :name, {:include_blank => 'Category'}) %>
</div>
<div class="field">
<%= f.collection_select(:group, Group.find(:all), :id, :name, {:include_blank => 'Group'}) %>
</div>
<div class="field">
<%= f.collection_select(:member, Member.find(:all), :id, :name, {:include_blank => 'Member'}) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
What would be the best way to make those fields dependent ? I found several topics regarding this on the web but could not really find an answer.
Upvotes: 5
Views: 7279
Reputation: 5791
The best way of doing it is AJAX call. In the starting just populate category drop-down. And on change of category make an ajax call and populate groups. And do same for the members on groups drop-down change.
Try something like this:
$("#category']").click(function(){
var url = '/get_drop_down_options?category_id=' + $(this).val()
$("#group").removeOption(/./)
$.get(url, function(data) {
$('#group').addOption(data, false);
});
});
In your controller:
def get_drop_down_options
val = params[:category_id]
#Use val to find records
options = YourModel.collect{|x| "'#{x.id}' : '#{x.label}'"}
render :text => "{#{options.join(",")}}"
end
Now you dont need partial.
Upvotes: 5
Reputation: 1621
I would have a different Id for each field, and use some jquery animation and ajax magic: When a field is clicked I would do an ajax call to retrieve all the records of the subgroup, once i got them, make appear that div with a slide down animation, or similar.
Upvotes: 0