问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/1519855/manually-instantiate-activerecord-models-and-their-relationships