问题
I am using materialize-sass gem on a form. Using autocomplete feature to get Vendor names. other fields on the form are item names and quantity which are a nested resource. For this I am using cocoon gem
For some reason the very first time the page loads, all seems to work fine. But adding more fields does not seem to be working. I tried using drop down select and that does not show the list of items. I replaced it with another autocomplete and the main field does show however the auto complete feature does not work. Any idea what may be wrong?
Please see my code below.
purchase_orders _forms.html.erb
<div class="col s12">
<%= simple_form_for(@purchase_order) do |f| %>
<%= f.error_notification %>
<div class="row">
<div class="col s6">
<%= f.input :vendor_name, input_html: { class: 'vendor_name autocomplete' } %>
</div>
</div>
<section class="show-section">
<div class="row">
<div class="col l12"><h4>Item List</h4></div>
<div class="col s12">
<%= f.simple_fields_for :purchase_order_details do |purchase_order_detail| %>
<%= render 'purchase_order_detail_fields', :f => purchase_order_detail %>
<div class="links">
<%= link_to_add_association 'Add More', f, :purchase_order_details %>
</div>
<% end %>
</div>
</div>
</section>
<%= f.button :submit %>
<% end %>
</div>
_purchase_order_detail_fields.html.erb
<div class="nested-fields">
<div class="row">
<div class="col l6">
<%#= f.input(:item_id, collection: Ingredient.is_active, label_method: :title, value_method: :id) %>
<%= f.input :item_name, input_html: { class: 'item_name autocomplete' } %>
</div>
<div class="col l5">
<%= f.input :item_quantity %>
</div>
<div class="col l1">
<%= link_to_remove_association "delete", f, :class => "material-icons teal-text text-lighten-1" %>
</div>
<%#= f.hidden_field :item_type , :value=> params[:category_id] %>
</div>
</div>
回答1:
Checking out the demo-project they use, and more specifically the init.js they use I notice two things: if you are using turbolinks you will have to do the same, and when using cocoon you will have to do something like:
$('form').on('cocoon:before-insert', function(e, insertedItem) {
$(insertedItem).find('select').material_select();
})
回答2:
This is the coffee script I used to be able to populate the autocompelte
$.ajax
url: '/packing_materials/by_name.json'
dataType: 'json'
success: (my_res) ->
$ ->
$('input.packing_material_name.autocomplete').autocomplete data: my_res
$(document).on 'cocoon:before-insert', ->
$.ajax
url: '/packing_materials/by_name.json'
dataType: 'json'
success: (my_res) ->
$ ->
$('input.packing_material_name.autocomplete').autocomplete data: my_res
来源:https://stackoverflow.com/questions/47235870/rails-materialize-sass-form-with-autocomplete-and-cocoon-gem-nested-resource