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

oor*_*ort 5 nested-attributes ruby-on-rails-3

我知道你可以:

accepts_nested_attributes_for :foo, :reject_if => proc { |a| a[:bar].blank? }
Run Code Online (Sandbox Code Playgroud)

有没有办法说出类似的话

accepts_nested_attributes_for :foo, :reject_if => blah[:bar].blank? and flah[:bar].blank?
Run Code Online (Sandbox Code Playgroud)

要么

accepts_nested_attributes_for :foo, :reject_if => all fields except record_date.blank?
Run Code Online (Sandbox Code Playgroud)

谢谢

m_x*_*m_x 9

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

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


小智 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)} }
Run Code Online (Sandbox Code Playgroud)

如果只有一个异常,则可以替换['foo', 'bar', 'baz'].include?(k)为,但第一个语法使过程准备好处理多个异常。k == 'foo'