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.
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.
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