开发者

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜