The find methods are very convenient for retrieving records, and I’m frequently using :include to prefetch referenced records to avoid expensive db accesses.
I have a case where I retrieve all sales by a salesperson.
@sales = Sales.find(:all,
:include => [:salesperson, :customer, :batch, :product],
:conditions => {:salesperson_id => someone},
:order => :customer_id)
I then want to slice and dice the returned records based on what was returned. For instance, I want to produce a report for all the sales made by this salesperson at a particular store, which we know is a subset of the previously returned data.
What I’d like to do is,
@storeSales = @sales.find_by_store(store_id)
…and retrieve this subset from the array held in memory as a new array, rather than achieve the same thing by performing a find on the database again. After all, @sales is just a array of Sales objects, so it doesn’t seem unreasonable that this should be supported.
However, it doesn’t seem that there’s a convenient way to do this, is there? Thanks.
If you are using Rails 3, @sales will be an AREL criteria object. What you can do is as follows:
Now @sales is an instance of an Array of Sales model objects. Getting a subset of the array objects is now easy using the select method:
Upon using select method you will now have @sales being the full result set and @my_product_sales being the subset based on the collect criteria.