Manually instantiate ActiveRecord models and their relationships?

随声附和 提交于 2019-12-10 19:07:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!