John Fadria
John Fadria

Reputation: 1945

Rails nested attributes with no creation if nested attributes are blank

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:

enter image description here

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

Upvotes: 0

Views: 725

Answers (1)

Deepesh
Deepesh

Reputation: 6398

You can add a validation like this:

accepts_nested_attributes_for :location, reject_if: proc { |l| l[:name].blank? }

or you can also create a method in the InventoryItem model when to reject and call like this:

accepts_nested_attributes_for :location, reject_if: :reject_method?

def reject_method(attributes)
  attributes['name'].blank?
end

Read more about the syntax here: https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Upvotes: 1

Related Questions