During my journey to update an old Go Rails video tutorial for selectize functionality to work with Rails 6, I encountered a challenge.
I have established a relationship where each item belongs to a series.
class Item < ApplicationRecord
belongs_to :series
end
A series, on the other hand, can have many items associated with it.
class Series < ApplicationRecord
has_many :items
end
In the item form, I am utilizing selectize for finding or creating a series.
<%= form_for @item do |form| %>
<div class="form-group">
<%= form.select :series_id, Series.all.pluck(:name, :id), {}, { class: "selectize" } %>
</div>
....
All seemed well until I hit an issue while trying to close the modal after creating a new series. The console threw an error that prevented the modal from closing.
<!-- Modal -->
<div class="modal fade series-modal" id="series-modal" tabindex="-1" role="dialog" aria-labelledby="SeriesModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="SeriesModal">Add series</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<%= form_for Series.new do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.collection_select(:account_id, Account.all, :id, :name ) %>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<%= f.submit class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
</div>
The JavaScript involved in handling the modal and form interactions is as follows:
<!-- JS -->
$(document).on("turbolinks:load", function() {
var selectizeCallback = null;
$(".series-modal").on("hide.bs.modal", function(e) {
if (selectizeCallback != null) {
selectizeCallback();
selectizeCallback = null;
}
$("#new_series").trigger("reset");
$.rails.enableFormElements($("#new_series"));
});
$("#new_series").on("submit", function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(response) {
selectizeCallback({value: response.id, text: response.name});
$(".series-modal").modal('toggle');
}
});
});
$(".selectize").selectize({
create: function(input, callback) {
selectizeCallback = callback;
$(".series-modal").modal();
$("#series_name").val(input);
}
});
});
It seems like there might be a glitch in my JavaScript code related to how Bootstrap handles the closure of modals now.
Your assistance in resolving this matter would be greatly appreciated.