Can reject_if be used to reject a nested resource

2019-03-29 12:25发布

I know that you can have:

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

Is there a way to instead 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?

Thanks

2条回答
2楼-- · 2019-03-29 12:41

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) by k == 'foo' if there's only one exception but the first syntax makes the proc ready for multiple ones.

查看更多
Melony?
3楼-- · 2019-03-29 12:46

I'm a bit late on this, but you can do :

accepts_nested_attributes_for :foo, 
                               reject_if: ->(attributes){ 
                                 attributes.except(:key).values.all?( &:blank? ) 
                               }
查看更多
登录 后发表回答