views:

56

answers:

4

So, I want to search in fetched records:

p = Product.added_today # Get records by scope

# wants something like
p.search(:name => 'Clocks')

Is there easy (rails way) to do it (gem or something)?

A: 

one way would be using ruby's find_all -

q = p.find_all{ |e| e.name == 'Clocks' }

as this this code uses brute force ruby array search, performance isn't great. if you expect p to contain more than a few tens of elements, using database queries would be better, performance wise.

amba
+1  A: 

You can use the following Rails features to mimic that kind of search.

  • In Rails 2 you can use Named Scopes
  • In Rails 3 you can use Arel (See the Readme section)
DR
+1  A: 

Try building on your scope:
Product.added_today.find(:all, :conditions => {:name => 'Clock'})

Faisal
No, I want to search in already fetched records!
rbnoob
This code only fetches what you want. However, if you already fetched rows, and now want to select some records, the only way I can think of is to iterate over all of them. Check amba's answer for that.
Faisal
+2  A: 

Try this:

pa =  Product.added_today
pa.select{|p| p.name == "Clocks"}
KandadaBoggu