Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails dependent collection_select fields in form

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.

like image 804
Luc Avatar asked Oct 11 '22 12:10

Luc


1 Answers

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.

like image 164
Ashish Avatar answered Oct 14 '22 09:10

Ashish