如果除了一个以外的所有字段都是空白,可以使用reject_if来拒绝嵌套资源吗?

时间:2012-06-18 17:53:34

标签: ruby-on-rails-3 nested-attributes

我知道你可以:

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

有没有办法说出类似

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

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

由于

2 个答案:

答案 0 :(得分:9)

我有点迟到,但你可以这样做:

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

答案 1 :(得分:0)

灵感来自:https://rails.lighthouseapp.com/projects/8994/tickets/2501-any_blank-and-all_blank-options-for-accepts_nested_attributes_for-reject_if

这对我来说很好:

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

如果只有一个例外,您可以将['foo', 'bar', 'baz'].include?(k)替换为k == 'foo',但第一个语法会使proc准备好多个。