Nested forms are nasty, but many times, a necessary evil 🙂
Rails tackled it since version 2.3x, when added the ActiveRecord method accepts_nested_attributes_for, main ref here. For its complexity, I believe, it is still hard to master it, and still bugs may happen; this was my lesson.
So, using the gem or not, still there are things to cover over this methods params;
From what I could observe, :reject_if, does not work for ‘rejecting’ a existing record, i.e.: those that have ID. But, it is called for those too! – In this topic, (what may be a bug) is that, if the record gets rejected, it does not get updated (it does not go through it’s model’s validations either).
The solution I found was not using :reject_if, instead, validating whatever I wanted on the nested Model in order to keep dry.
For this scenario, consider the following setup (rails v3.0.5)
class A < ActiveRecord::Base has_many :bs accepts_nested_attributes_for :bs, :allow_destroy => true #no use. :reject_if => :combo_elem_zero? # wont use this function at all def combo_elem_zero?( att ) #puts(atribs.to_yaml) #att['_destroy'] = '1' # wont work here # only useful for new records if atribs['id'].blank? && att[:some_atrib].to_f < something_blah true else false end end end class B < ActiveRecord::Base belongs_to :a validate :destruction_update # works both for create/update def destruction_update if self.some_atrib.to_f < something_blah self.mark_for_destruction end end end
If on the other hand, you only need to check on the nested new records, :reject_if may do the job.