I'm using the Dependent-Fields gem. It's basically JavaScript, that reacts on the "js-dependent-fields" class. The following code works as intended:
<div class="panel-body">
<div class="form-group">
<%= f.label :brand %>
<%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
</div>
<% Brand.all.each do |b| %>
<div class="form-group js-dependent-fields" data-option-value="<%= b.company %>" data-select-id="warehouse_brand">
<%= f.label :category %>
<%= f.collection_select(:category, Group.where(brand: b.company), :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
</div>
<% end %>
The thing is the loop creates the right amount of div's (each) with a style="display:none;"
. But when I want to save the form, Rails gets confused because there are multiple "category" form fields. The result is: nothing gets saved in the "category" record. The HTML output:
<div class="form-group">
<label for="warehouse_brand">Brand</label>
<select class="form-control" name="warehouse[brand]" id="warehouse_brand">
<option selected="selected" value="Adidas">Adidas</option>
<option value="Nike">Nike</option>
<option value="Fila">Fila</option>
</div>
<div class="form-group js-dependent-fields" data-option-value="Adidas" data-select-id="warehouse_brand" style="">
<label for="warehouse_category">Category</label>
<select class="form-control" name="warehouse[category]" id="warehouse_category">
<option value="">Please select</option>
<option value="Adidas">Shoes</option>
<option value="Adidas">Shirts</option>
</select>
</div>
<div class="form-group js-dependent-fields" data-option-value="Nike" data-select-id="warehouse_brand" style="display: none;">
<label for="warehouse_category">Category</label>
<select class="form-control" name="warehouse[category]" id="warehouse_category">
<option value="">Please select</option>
</select>
</div>
<div class="form-group js-dependent-fields" data-option-value="Fila" data-select-id="warehouse_brand" style="display: none;">
<label for="warehouse_category">Category</label>
<select class="form-control" name="warehouse[category]" id="warehouse_category">
<option value="">Please select</option>
</select>
</div>
I guess that Rails does not know which of the form fields has to be saved because of the loop (which is necessary unfortunately). Do you have a solution for that?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…