0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks @deepesh, my problem now is that Location must exist
You can add validates_presence_of :location to check that on the InventoryItem model
Sorry @deepesh with this validation I optain two errors now. Location must exist and Location can't be blank If is blank I want to create the InventoryItem without a Location
Location can't be blank is from the validation we have added above, the must exist is from the belongs_to association.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.