Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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]
Add Comment
Please, Sign In to add comment