How to optimise the code

16 views
Skip to first unread message

Hem Chan

unread,
Jun 7, 2016, 9:06:55 PM6/7/16
to rubyonra...@googlegroups.com
How would I optimize the following code?

def posts_for_30_blogs
blogs = Blog.limit(30)
blogs.flat_map do |blog|
blog.posts.to_a
end
end

--
Posted via http://www.ruby-forum.com/.

Greg Navis

unread,
Jun 8, 2016, 12:25:58 AM6/8/16
to rubyonra...@googlegroups.com
Optimise in what sense? If this is about solving the N + 1 query problem then try:

blogs = Blog.include(:posts).limit(30)

This should load associated posts with only 1 query.
--
Greg Navis
I help tech companies to scale Heroku-hosted Rails apps.

Hem Chan

unread,
Jun 8, 2016, 12:31:50 AM6/8/16
to rubyonra...@googlegroups.com
Thanks very much..
Reply all
Reply to author
Forward
0 new messages