views:

154

answers:

1

If I have T-SQL (or a stored proc) that returns records from multiple tables (using DBI perhaps), is there a way for me to manually instantiate the ActiveRecord models and their associations? Obviously, I’m after database performance here. I would like to be able to build my own object hierarchy (models and their relationships), but when I’m all done I would expect each model to behave normally. That is, I am hoping this would be accomplished without some hack that might cause my structure to behave oddly.

EDIT:

This is a little contrived but it does illustrate how one query could return data n levels deep (where "n" has only practical limits) and return everything in one call to the database:

SELECT * FROM customers 
  WHERE id = 1;

SELECT * FROM orders 
  WHERE customer_id = 1;

SELECT * FROM lineitems 
  WHERE order_id IN (
  SELECT id FROM orders 
    WHERE customer_id = 1
  );

And then having all of the records I would simply map the associations myself. The problem with doing this via ActiveRecord and :include is that it will hit the database multiple times instead of just once--which is more taxing as "n" increases.

A: 

If I understand what you're getting at, you're trying to execute multiple sql queries at once and still have Rails return all the instantiated models as it normally would.

What you really want is:

Customer.find(:all, :include => {:orders => :lineitems})

Which will fetch all the records your interested in in a single query and create the AR objects properly.

Steven Soroka
I should add, anything more complicated than that (like stored procedures) is probably wasting your time. It sounds like you're trying to optimize prematurely. You're going to spend all your time fussing over a few milliseconds here or there (which probably wont matter, anyway) and never finish/launch a product.
Steven Soroka
You're right--I have given up on premature optimization. I have some structures that can't really be handled by the :include option, because of multiple levels of polymorphic relationships. Take your example. What if "orders" was a polymorphic object which sometimes has lineitems and sometimes not? This is not a great example, I admit, however in doing the same, I've rendered :include useless.
Mario