Skip to content

Instantly share code, notes, and snippets.

@a-suenami
Created April 12, 2018 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-suenami/b83b91ffeb329439211e34f5e002b2ee to your computer and use it in GitHub Desktop.
Save a-suenami/b83b91ffeb329439211e34f5e002b2ee to your computer and use it in GitHub Desktop.
Effect of includes and merge to associations
# CREATE DATABASE demo CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
# USE demo;
# CREATE TABLE articles (id BIGINT PRIMARY KEY);
# CREATE TABLE comments (id BIGINT PRIMARY KEY, article_id BIGINT NOT NULL, status SMALLINT NOT NULL);
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'mysql2',
host: 'localhost',
username: 'root',
password: '',
database: 'demo'
)
class Article < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
scope :published, -> { where(status: 1) }
end
Article.find_or_create_by(id: 1)
Comment.find_or_create_by(id: 1, article_id: 1, status: 1)
Comment.find_or_create_by(id: 2, article_id: 1, status: 0)
Comment.find_or_create_by(id: 3, article_id: 1, status: 1)
Comment.find_or_create_by(id: 4, article_id: 1, status: 0)
Comment.find_or_create_by(id: 5, article_id: 1, status: 1)
articles1 = Article.joins(:comments).includes(:comments).merge(Comment.published)
articles2 = Article.joins(:comments).includes(:comments)
puts articles1.first.comments.map(&:status).inspect #=> [1, 1, 1]
puts articles2.first.comments.map(&:status).inspect #=> [1, 0, 1, 0, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment