Guest User

Untitled

a guest
Apr 20th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. # CREATE DATABASE demo CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
  2. # USE demo;
  3. # CREATE TABLE articles (id BIGINT PRIMARY KEY);
  4. # CREATE TABLE comments (id BIGINT PRIMARY KEY, article_id BIGINT NOT NULL, status SMALLINT NOT NULL);
  5.  
  6. require 'active_record'
  7.  
  8. ActiveRecord::Base.establish_connection(
  9. adapter: 'mysql2',
  10. host: 'localhost',
  11. username: 'root',
  12. password: '',
  13. database: 'demo'
  14. )
  15.  
  16. class Article < ActiveRecord::Base
  17. has_many :comments
  18. end
  19.  
  20. class Comment < ActiveRecord::Base
  21. scope :published, -> { where(status: 1) }
  22. end
  23.  
  24. Article.find_or_create_by(id: 1)
  25.  
  26. Comment.find_or_create_by(id: 1, article_id: 1, status: 1)
  27. Comment.find_or_create_by(id: 2, article_id: 1, status: 0)
  28. Comment.find_or_create_by(id: 3, article_id: 1, status: 1)
  29. Comment.find_or_create_by(id: 4, article_id: 1, status: 0)
  30. Comment.find_or_create_by(id: 5, article_id: 1, status: 1)
  31.  
  32. articles1 = Article.joins(:comments).includes(:comments).merge(Comment.published)
  33. articles2 = Article.joins(:comments).includes(:comments)
  34.  
  35. puts articles1.first.comments.map(&:status).inspect #=> [1, 1, 1]
  36. puts articles2.first.comments.map(&:status).inspect #=> [1, 0, 1, 0, 1]
Add Comment
Please, Sign In to add comment