I’d like to suggest adding a stronger version of the :reject_if option to the .accepts_nested_attributes_for class method, one that not only prevents new records from being added, but also destroys existing records, using the same supplied logic.
Use-case:
A person has many email addresses, and the person wants to update their profile by adding and removing email addresses in a form. This form is designed to be a simple list of text fields, one for each email address. Users can update an existing email address by simply editing the text field, create a new email address by filling in a new text field, and remove existing email addresses by clearing out a text field. Simplicity and consistency is the goal here.
However, .accepts_nested_attributes_for’s :reject_if option only permits 2/3 of these use-cases, so I have created a gem that adds a new :destroy_if option, and this permits all three use-cases! I am posting here to see if there is interest in merging this (in one form or another) into ActiveRecord itself. More details are in the README of the gem:
Hi Mehmet! That’s great to hear! I had tried accomplishing this via lifecycle hooks, and then via setters, and found that it was really hard to cover all the edge cases, and that it felt like I was fighting with the functionality in .accepts_nested_arguments_for. Glad to hear that its not just me who has a use for this. Knowing that you’re using it, I’ll fill out the Travis testing matrix to test more rubies and rails, instead of just the combo my app is using.
Okay, just released version v0.2.0, which expands support to Ruby 2.5, 2.6, and 2.7, and Rails 5.1, 5.2, and 6.0. No changes to the code needed to be made, it turns out. Probably works on older Rubies and Rails, too, but this was the low hanging fruit. PRs welcome for more support.
Rails core folks: would submitting a PR at this point be premature? I’m not clear on how this process works.
My understanding is that :allow_destroy simply enables the _destroy param. Is this not the case, and I'm reinventing existing functionality?
Rereading the documentation, it appears as though my understanding is correct. If it's not, though, that would be great. I'd love to already have this functionality!
Yes, I could write some JavaScript to inspect the text fields on their change event, and then toggle a hidden _destroy param to cover the third use-case, but this has some significant downsides, compared to :destroy_if solution that I’m proposing here.
Decreased locality. Logic to handle nested params would be both in the model, and also in the client in JavaScript
Increased complexity. The JavaScript component is more lines of code, and thus more things that can go wrong. What if the client is running NoScript, etc?
Code duplication. The predicate logic that is passed to :ignore_if would have to also be written in JavaScript.
Compared to this, :destroy_if appears to be a much simpler and cleaner solution, and has none of these downsides.