手动实例ActiveRecord模型和它们之间的关系? [英] Manually instantiate ActiveRecord models and their relationships?

查看:107
本文介绍了手动实例ActiveRecord模型和它们之间的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有T-SQL(或存储过程),返回从多个表(使用DBI也许)的记录,有没有办法对我来说,手动实例ActiveRecord模型及其关联?很显然,我在这里后,数据库性能是。我希望能够建立自己的对象的层次结构(模型和它们之间的关系),但是当我做了所有我希望每个模型正常行为。也就是说,我希望这将是没有一些黑客工具,可能会导致我的结构,行为古怪完成。

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.

编辑:

这是一个有点做作,但它确实说明了如何一个查询可以返回数据n层深(其中n只有实际的限制),并在一个调用返回的一切数据库:

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
  );

然后让所有的记录,我想简单地映射协会自己。该问题通过ActiveRecord的这样做的,:包括是它将击中数据库多次,而不是仅仅一次 - 这是比较费力的为n的增加

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.

推荐答案

如果我明白你在说什么,你想在一次执行多个SQL查询,仍然有滑轨返回所有的实例化模型,因为它通常会的。

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.

你真正想要的是什么:

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

这将获取中的所有记录你的兴趣在一个单一的查询和创建AR正当理由反对。

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

这篇关于手动实例ActiveRecord模型和它们之间的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆