Searching ActiveRecord sets

Hey all,

I’m learning AR and I’m trying to find the best way to search an
ActiveRecord set in order to make a conditional statement decision,
something like .has_value?(value) but for a multi-dimensional array like
an AR set of like 100 rows.

I know I can do something like this:

results = Table.find_by_sql("…")

for result in results
if result.has_value?(“value”)
do something…
end
end

But I’d rather not iterate through every row of results to find out. I
think I read somewhere about being able to use the .find method to
search AR hashes? Something like: results.find(…) but I’m not able to
find more info on that.

I want to be able to have a conditional statement and only have it run
if there is an attribute somewhere in the AR set that matches a given
value. Thanks for any help and suggestions in advance.

results is just a Ruby array of AR objects. Have a look at what you
can do with arrays in Ruby:

http://www.ruby-doc.org/core/classes/Array.html

Methods like select, reject, collect, delete_if may be useful for you.

What exactly are you trying to achieve… more specifics would be
useful.

-Jonathan.

Yes,

Basically I want an easy way to search the AR set for a condition and do
something if that condition is met, ANYWHERE in the AR result set.

But it seems methods like .has_value?, .has_key?, .include? etc are
specific for single arrays and hashes and not a multi-dimensional
array/hash such as an AR result set.

There might be a simple method I’m over looking though, but I guess
thats what I’m looking for :slight_smile:

So from my previous examples:

results = Table.find_by_sql("…")

for result in results
if result.has_value?(“value”)
do something…
end
end

Instead I’d like to do something like this to save resources and not
start an iteration into the for loop at all unless the condition is met:

results = Table.find_by_sql("…")

if results.has_value?(“value”)
do something…
end

Though as I mentioned above, .has_value? doesn’t seem to work on AR
result sets, so I’m looking for something that does and works similarly
Hope that made some sense. Thanks

Jonathan,

Great, thanks alot. I think thats what I’m looking for and the tip
about you just having to iterate over results. Thanks.

Jonathan V. wrote:

Have a look at any?

module Enumerable - RDoc Documentation

if results.any? { |r| … }

do something

end

You’ll always have to iterate over results. There’s no other way to
look at all the values …

-Jonathan.

Have a look at any?

http://www.ruby-doc.org/core/classes/Enumerable.html#M003125

if results.any? { |r| … }

do something

end

You’ll always have to iterate over results. There’s no other way to
look at all the values …

-Jonathan.