I have a nested attributes between:
class InventoryItem < ApplicationRecord
belongs_to :location
accepts_nested_attributes_for :location
end
class Location < ApplicationRecord
has_many :inventory_items
has_many :bins
accepts_nested_attributes_for :bins
end
class Bin < ApplicationRecord
belongs_to :location
end
The inventory_item
form:
<%= form.fields_for :location do |location| %>
<div class="field">
<%= location.label :location_name %>
<%= location.text_field :name %>
</div>
<%= location.fields_for :bins do |bin| %>
<div class="field">
<%= bin.label :bin_name %>
<%= bin.text_field :name %>
</div>
<% end %>
</div>
<% end %>
And in the inventory_item
controller:
def new
@inventory_item = InventoryItem.new
@inventory_item.build_location.bins.build
end
def inventory_item_params
params.require(:inventory_item).permit(:location_id, location_attributes:[:name, bins_attributes:[:name]])
end
The form:
My issue is that I can create an InventoryItem
with a Location
and Bin
name blank and it creates a new Location
and Bin
and the corresponding association between InventoryItem
and a blank Location
.
I want that when Location
name or Bin
name are blank in the form a new Location
, a new Bin
and the association will not be created.
Thanks in advance