Alex
Alex

Reputation: 419

Setting a limit to the number of associated records in nested forms

I have a nested form with the following structure:

I run a validation in the list model to make sure that each list only has a maximum of ten items.

validate :max_stack_items

def max_stack_items
  if items.size > 10
    errors[:base] << "Stack cannot have more than 10 items"
end

This works fine 90% of the time. I implemented a feature so you can delete list items within the list form as follows:

<%= f.hidden_field :_destroy %>
<%= link_to "remove item", '#', class: "remove_fields" %>

I have some associated javascript that makes this happen (not important for the question).

Let's say I have 10 list items already and I go to edit the form. If I delete one of the list items by clicking on the "remove item" link and add a new list item. The validation fails, since it thinks there are more than 10 list items. In other words, it doesn't realize that I have removed one list item and added another one at the same time (so that there are still only 10 list items).

How can I get the validation to take into account what list item records I'm deleting at the same time?

Upvotes: 0

Views: 648

Answers (1)

Alex
Alex

Reputation: 419

def max_stack_items
  if restaurants.reject(&:marked_for_destruction?).size > 10
    errors[:base] << "Stack cannot have more than 10 items"
  end
end

This solution takes into account the items that are marked for destruction during the validation.

Upvotes: 5

Related Questions