2

假设,我有 2 个不同的模型;用户和帖子。我想获得每个用户的最新帖子。所以输出将是这样的。

[<Post user_id:1, content:"yadayada" ....>, <Post user_id:2, content:"blabla"...> ......]

每个用户不超过一个记录是我有点困惑的部分。我用谷歌搜索了一下,发现复杂的活动记录查询来处理这个问题。我想知道是否有任何简单的rails3.present? ? "rails3" : "rails"方法。

感觉这不应该超过 1 行代码。提前致谢。

4

2 回答 2

3

Seeing as I cannot yet post comments, here is the answer to eager loading:

The N+1 problem means that ActiveRecord will not get the posts, when you query for all your users using User.all, therefore ActiveRecord will fire a new SQL query that selects the last post for every single user you iterate over. If you have 50 users, that will be one query for the fifty users and then fifty queries for each last post.

In case you have many users, the latency between the database and the Rails application will slow down the performance of the site and make users wait.

Eager loading allows you to fetch associated models to the model you are querying, so you can write:

User.includes(:posts).all.map { |u| u.posts.last }

ActiveRecord will first query for all the users, then query for all posts associated with all the users at once before iterating over the users, thereby avoiding doing a new query for each user. This is only two queries.

However, this also has it's drawbacks if your users have tons of posts, because you'll be fetching ALL posts of ALL users and not just the latest posts, thereby straining the database and generating a lot of undesired I/O.

于 2012-12-01T20:15:42.413 回答
1
posts = User.all.map { |u| u.posts.last }
于 2012-12-01T19:11:15.443 回答