Can reject_if be used to reject a nested resource if all fields except one are empty?

I know you can:

accepts_nested_attributes_for :foo, :reject_if => proc { |a| a[:bar].blank? }

Is there a way instead to say something like

accepts_nested_attributes_for :foo, :reject_if => blah[:bar].blank? and flah[:bar].blank?

or

accepts_nested_attributes_for :foo, :reject_if => all fields except record_date.blank?

thank

+5
source share
2 answers

I'm a little late for this, but you can do:

accepts_nested_attributes_for :foo, 
                               reject_if: ->(attributes){ 
                                 attributes.except(:key).values.all?( &:blank? ) 
                               }
+9
source

Inspired by this: https://rails.lighthouseapp.com/projects/8994/tickets/2501-any_blank-and-all_blank-options-for-accepts_nested_attributes_for-reject_if

This worked fine for me:

reject_if: proc { |attributes| attributes.all? {|k,v| v.blank? || ['foo', 'bar', 'baz'].include?(k)} }

You can replace ['foo', 'bar', 'baz'].include?(k)with k == 'foo'if there is only one exception, but the first syntax causes proc to prepare for several.

0
source

All Articles