简体   繁体   English

Rails:渴望获取关联,而不是查找

[英]Rails: eager load on fetching associations, not on find

I've got three nested models: user has many plates and plate has many fruits . 我有三个嵌套模型: user有很多platesplate有很多fruits I also have a current_user helper method that runs in the before filter to provide authentication. 我还有一个current_user帮助器方法,该方法在before过滤器中运行以提供身份验证。 So when I get to my controller, I already have my user object. 因此,当我到达控制器时,我已经有了我的user对象。 How can I load all the user's plates and fruits at once? 如何一次加载所有用户的platesfruits

In other words, I'd like to do something like: 换句话说,我想做些类似的事情:

@plates = current_user.plates(include: :fruits)

How can I achieve this? 我该如何实现?

I'm using Rails 3.1.3. 我正在使用Rails 3.1.3。

You will probably want to use the provided #includes method on your relation. 您可能需要在关系上使用提供的#includes方法。 DO NOT USE #all unless you intend to immediately work through the records, it will immediately defeat many forms of caching. 除非您打算立即处理记录,否则不要使用#all ,它会立即破坏许多形式的缓存。

Perhaps something like: @plates = current_user.plates.includes(:fruits) 也许像这样: @plates = current_user.plates.includes(:fruits)

Unfortunately, there are portions of the Rails API that are not as well documented as they should be. 不幸的是,Rails API的某些部分没有得到应有的详细记录。 I would recommend checking out the following resources if you have any further questions about the Rails query interface: 如果您对Rails查询界面还有其他疑问,我建议您检查以下资源:

The query interface is possibly the most difficult part of the Rails stack to keep up with, especially with the changes made with Rails 3.0 and 3.1. 查询界面可能是Rails堆栈中最困难的部分,尤其是在Rails 3.0和3.1所做的更改中。

You can do 你可以做

ActiveRecord::Associations::Preloader.new([current_user], :plates => :fruit).run

To eager load associations after current_user was loased. 松散current_user之后,急于进行负载关联。 The second argument can be anything you would normally pass to includes : a symbol, an array of symbols, a hash etc 第二个参数可以是通常传递给includes任何东西:符号,符号数组,哈希等

@plates = current_user.plates.all(:include => :fruits)

应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM