How to avoid short-circuit evaluation on

允我心安 提交于 2019-12-03 10:28:47

Try this:

([model1, model2].map(&:valid?)).all?

It'll return true if both are valid, and create the errors on both instances.

& works just fine.

irb(main):007:0> def a
irb(main):008:1> puts "a"
irb(main):009:1> false
irb(main):010:1> end
=> nil

irb(main):011:0> def b
irb(main):012:1> puts "b"
irb(main):013:1> true
irb(main):014:1> end
=> nil

irb(main):015:0> a && b
a
=> false

irb(main):016:0> a & b
a
b
=> false

irb(main):017:0> a and b
a
=> false

How about:

if [model1.valid?,model2.valid?].all?
  ...
end

Works for me.

Evaluate them separately and store the result in a variable. Then use a simple && between those booleans :)

Instead of creating an extra array with map, you can pass a block to all?.

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