I'm working with a Rails application that has a many-to-many association between the dream and location models, linked via a dream_location join model. When creating a new dream, I want to allow multiple locations to be added at once using tom-select. However, the form is submitting a blank/empty location_id along with valid selections, which is causing the save to fail.
I have tried to remove the blank option on the JS side with the following code:
// Initialize Tom Select on the relevant fields
document.addEventListener('DOMContentLoaded', () => {
const elements = document.querySelectorAll('.tom-select');
elements.forEach((element) => {
new TomSelect(element, {
create: false,
onInitialize: function() {
// Remove the blank option if it exists
const blankOption = this.getOption('');
if (blankOption) {
this.removeOption('');
}
}
});
});
});
The related form code in my ERB view looks like this:
<h3>Locations</h3>
<%= form.fields_for :dream_locations do |dl_form| %>
<div class="form-group">
<%= dl_form.collection_select :location_id, Location.where(user_id: current_user.id), :id, :name,
{},
{ :multiple => true, class: "form-control tom-select" } %>
<%= dl_form.check_box :_destroy %>
<%= dl_form.label :_destroy, "Remove this location" %>
</div>
<% end %>
When the form is submitted, I receive parameters like the following (including the unwanted blank location_id):
{"authenticity_token" => "[FILTERED]",
"dream" => {"title" => "Dream 2346", "date" => "2025-01-06",
"location" => "Some Other Location", "dream_locations_attributes" =>
{"0" => {"location_id" => ["", "3"], "_destroy" => "0"}}}, "dream" => "fewfwe", "analysis" => "rewr"}
I need guidance on how to modify the form or the JavaScript so that the blank location_id is not sent on submission. Any ideas or best practices to fix this?