views:

33

answers:

3

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?

A: 

Wow that is over complicating a simple task. How about

def some_func(arr)
  !arr.include?(false)
end

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.

Ed Swangren
How would I implement that in my Proc.new?
Trip
+1  A: 

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.

validates_presence_of :email, 
       :unless => Proc.new { organizations.exists?(:contact_24 => false)}

If you still insist on performing this at the client side then:

validates_presence_of :email, 
       :unless => Proc.new { organizations.any?{|o| o.contact_24 != true}}
KandadaBoggu
+1  A: 

OK, so your proc:

org.contact_24

Select will just return an array... So you need to return true if all org.contact_24 are true.

validates_presence_of :email, :if => Proc.new { |user| user.organizations.find(:all).collect {|org| org unless org.contact_24}.compact.blank? }

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:

user.organizations.not_contacted_in_24_hours
Jesse Wolgamott