Forum: Ruby on Rails Can you run a find on an existing hash?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C65fbc91799a72e3363a8031ea0c41e5?d=identicon&s=25 Robert Scott (rscott239)
on 2009-04-23 07:10
This is probably a basic question, but I was wondering if / how it's
possible to run a find on an existing hash.

For instance:

1. I need to pull all products in the database for a simple list:
@products = Products.find(:all)

2. At a separate portion of the page, I want to display products that
are in, say, category 5.

From scratch, I could run...
@new_products = Products.find(:all, :conditions => {:category_id => 5})

Although, I thought you could also do

@new_products = @products.find(:all, :conditions => {:category_id = 2})

My query has been returning a wrong number of arguments (2 for 1), so I
wasn't sure if I was headed on the right track.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-04-23 09:11
(Received via mailing list)
On Apr 23, 6:10 am, Robert Scott <rails-mailing-l...@andreas-s.net>
wrote:
>
> From scratch, I could run...
> @new_products = Products.find(:all, :conditions => {:category_id => 5})
>
> Although, I thought you could also do
>
> @new_products = @products.find(:all, :conditions => {:category_id = 2})
>
> My query has been returning a wrong number of arguments (2 for 1), so I
> wasn't sure if I was headed on the right track.

Enumerables (and thus arrays) have a method called find, but it's not
an activerecord find and so has different syntax. Check the ruby
standard library api for details of enumerable's find.

Fred
84fbb9c2a7b05c3ddf39904514585a90?d=identicon&s=25 Franco Catena (Guest)
on 2009-04-23 13:26
(Received via mailing list)
In the Enumerable's find_all method will be:

@products.find_all { |product| product.category_id = 2 }

This method returns an array, the find method returns only the first
match. This approach is not the best if you have a lot of products, in
that case you will use the ActiveRecord's find and let the database do
this work in a more efficient way.

Regards.

Franco Catena.

On Apr 23, 2:10 am, Robert Scott <rails-mailing-l...@andreas-s.net>
This topic is locked and can not be replied to.