LoginSignup
10
5

More than 1 year has passed since last update.

RailsでSQLを発行するメソッドと発行しないメソッド

Last updated at Posted at 2019-09-02

SQLが発行されるActiveRecordのメソッド、SQLが発行されないRubyのメソッドをまとめました
これであなたもRailsスペシャリストです!!!

スタートアップの段階では、SQLを発行した方が早いケースもありますが、経験上不必要なクエリの発行は控えた方がよいです。
ここではActiveRecord::Relationのことも配列と言ってます

配列の絞り込み

SQLが発行されるパターン: AR.where


class Article < ApplicationRecord
  enum ['published', 'unpublished']
end

published_articles = Article.where(state: 'published')
unpublished_articles = Article.where(state: 'unpublished')

Select *
from articles
where state = published

Select *
from articles
where state = unpublished


SQLが発行されないパターン: Array.select

articles = Article.all

articles.select { |a| a.state == 'published' }
articles.select { |a| a.state == 'unpublished' }

Select *
from articles

リファクタリング前のコード

# controller
@user = User.all

- @user.each do |user|
  - user.articles.where(state: 'published').each do |article|
    p = article.title

リファクタリング後のコード

# controller
@user = User.all

- @user.each do |user|
  - user.articles.select { |a| a.state == 'published' }.each do |article|
    p = article.title

配列から絞り込んで一つの要素取り出し

SQLが発行されるパターン: .find_by, .find

Article.find_by(title: 'ラーメンの美味しい食べ方')

SQLが発行されないパターン: .detect

aliasにfindがあり、ブロックの違いで分かりはしますが、ActiveRecordのメソッドと混同されるのでdetectを使うのがよいです

Article.all.detect { |article| article.title ==  'ラーメンの美味しい食べ方' }

配列をグルーピング

SQLが発行されるパターン: .group_by

group_by(&:state)['published']

SQLが発行されないパターン: .index_by

index_by(&:state)['published']

配列を並び替え

SQLが発行されないパターン: .order

order(id: :asc)

SQLが発行されるパターン: .sort_by

sort_by(&:id)

複雑な条件を1回で取得する

2回SQLが発行される例

published_articles = Article.where(state: 'published')
other_articles = Article.where.not(state: 'published')

リファクタリング後、1回のSQLで取得

published_articles, other_articles = Article.all.partition { |a| a.state == 'published' }
10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5