Filtering through an array of ActiveRecord objects

Hiya,

I have an array of ActiveRecord objects, I need to grab all records
from the array where “section = ‘foo’”. I’m doing it this way because
I don’t want to have to perform two find_by_XXX queries.

I successfully did this a while ago but I have forgotten since and
don’t have the source code handy. Any help would be appreciated.

Thanks.

On Feb 25, 11:44 pm, chris loper [email protected] wrote:

Hiya,

I have an array of ActiveRecord objects, I need to grab all records
from the array where “section = ‘foo’”. I’m doing it this way because
I don’t want to have to perform two find_by_XXX queries.

I successfully did this a while ago but I have forgotten since and
don’t have the source code handy. Any help would be appreciated.

Thanks.

Something like

filtered = array.collect { |element| element if element ==
‘foo’ }.compact

HTH,
–Dean

chris loper wrote the following on 26.02.2007 08:44 :

Hiya,

I have an array of ActiveRecord objects, I need to grab all records
from the array where “section = ‘foo’”. I’m doing it this way because
I don’t want to have to perform two find_by_XXX queries.

I may not understand your problem, but can’t you
find_by_xxx_and_section(<xxx_value>, ‘foo’)?

chris loper wrote:

Hiya,

I have an array of ActiveRecord objects, I need to grab all records
from the array where “section = ‘foo’”. I’m doing it this way because
I don’t want to have to perform two find_by_XXX queries.

I successfully did this a while ago but I have forgotten since and
don’t have the source code handy. Any help would be appreciated.

Thanks.

You can do this:

objects = array.select { |obj| obj.section == ‘foo’ }

-bob

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs