Skip to content

Instantly share code, notes, and snippets.

@jturkel
Last active August 29, 2015 14:02
Show Gist options
  • Save jturkel/0a1399b0bf916f45d295 to your computer and use it in GitHub Desktop.
Save jturkel/0a1399b0bf916f45d295 to your computer and use it in GitHub Desktop.
> blogs = Blogs.limit(5).to_a
# SELECT * FROM blogs LIMIT 5
> blogs.each { |blog| blog.posts.to_a }
# SELECT * FROM posts WHERE blog_id IN (1,2,3,4,5)
> blogs = Blogs.limit(5).to_a
# SELECT * FROM blogs LIMIT 5
> blogs.each do |blog|
if blog.posts.empty?
render_empty_blog
else
render_posts(blog.posts)
end
end
# SELECT COUNT(*) FROM posts WHERE blog_id = 1
# SELECT * FROM posts WHERE blog_id IN (1,2,3,4,5)
class Blog < ActiveRecord::Base
has_many :posts, fully_load: true
end
<h1>Recent <%= @blog.name %> Posts</h1>
<ul>
<% @posts.each do |post| %>
<li><%= post.title %><li>
<% end %>
<ul>
<h1>Recent <%= @blog.name %> Posts</h1>
<ul>
<% @posts.each do |post| %>
<li><%= post.title %> - <%= post.author.name %><li>
<% end %>
<ul>
class Blog < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :blog
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
end
class PostsController < ApplicationController
def index
@blog = Blog.find(params[:blog_id])
@posts = @blog.posts.order(published_at: :desc).limit(5)
end
end
class PostsController < ApplicationController
def index
@blog = Blog.find(params[:blog_id])
@posts = @blog.posts.includes(:author).order(published_at: :desc).limit(5)
end
end
SELECT * FROM posts WHERE blog_id = 1 ORDER BY published_at DESC LIMIT 5
SELECT * FROM authors WHERE id = 1 LIMIT 1
SELECT * FROM authors WHERE id = 2 LIMIT 1
SELECT * FROM authors WHERE id = 3 LIMIT 1
SELECT * FROM authors WHERE id = 4 LIMIT 1
SELECT * FROM authors WHERE id = 5 LIMIT 1
SELECT * FROM posts WHERE blog_id = 1 ORDER BY published_at DESC LIMIT 5
SELECT * FROM authors WHERE id IN (1,2,3,4,5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment