如何从 Rails 中的选择条件返回真/假语句
我正在尝试选择一个数组,并检查数组中是否有任何对象为 false。如果其中任何一个是 false,我想要返回 false 的最终值。
如果所有这些都是 true,我希望返回 true。
这就是我所拥有的。
validates_presence_of :email, :if => Proc.new { |user| user.organizations.find(:all).select {|org| org.contact_24} }
不幸的是,这只是返回数组。
你会怎么做?
I am trying to select an array, and check and see if any of the objects within the array are false. If any of them are false, I want an ultimate value of false returned.
If all of them are true, I want true returned..
Here's what I have..
validates_presence_of :email, :if => Proc.new { |user| user.organizations.find(:all).select {|org| org.contact_24} }
This unfortunately just returns the array.
How would you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
exists?
方法在数据库中执行检查。这确保了所有计算都是在数据库而不是客户端代码上完成的。如果您仍然坚持在客户端执行此操作,那么:
Perform the check in the DB, using the
exists?
method. This ensures all the calculations are done at the DB rather than the client code.If you still insist on performing this at the client side then:
好的,所以你的 proc:
Select 将只返回一个数组...所以如果所有 org.contact_24 都为 true,你需要返回 true。
这将构建一个包含 contact_24 为 false 的组织数组。然后它压缩数组,如果为空则返回 true。
因此,如果任何记录不真实,则该记录将是错误的。
我建议移动 Organizations.find(:all).collect {|org| org 除非 org.contact_24}.compact.blank?进入范围,所以你最终会得到:
OK, so your proc:
Select will just return an array... So you need to return true if all org.contact_24 are true.
That'll build an array of org's that have contact_24 that are false. It then compacts the array, and returns true if it's blank.
So, it'll be false if any records aren't true.
I'd recommend moving the organizations.find(:all).collect {|org| org unless org.contact_24}.compact.blank? into a scope, so you'd end up with:
哇,这让一项简单的任务变得过于复杂了。怎么样,
也许我错过了一些东西......但问题只是问如何返回“假”是一个包含“假”的数组,这就是它的作用。
Wow that is over complicating a simple task. How about
Maybe I am missing something... but the question just asks how to return 'false' is an array includes 'false', and that's what this does.