Can reject_if be used to reject a nested resource if all fields except one is blank?

假装没事ソ 提交于 2019-12-04 23:51:30

问题


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


回答1:


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? ) 
                               }



回答2:


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.



来源:https://stackoverflow.com/questions/11088331/can-reject-if-be-used-to-reject-a-nested-resource-if-all-fields-except-one-is-bl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!