Rails開発のtips
require 'rails/all'について
Railsアプリケーションを開発する際、config/application.rbでよく見かけるのがrequire 'rails/all'という記述です。この記述は、Railsの主要なコンポーネントをすべて読み込むための重要な設定です。
何が読み込まれるのか
require 'rails/all'
を実行すると、以下のRailsコンポーネントが読み込まれます:
require "rails"
[
"active_record/railtie",
"active_storage/engine",
"action_controller/railtie",
"action_view/railtie",
"action_mailer/railtie",
"active_job/railtie",
"action_cable/engine",
"action_mailbox/engine",
"action_text/engine",
"rails/test_unit/railtie"
].each do |railtie|
begin
require railtie
rescue LoadError
end
end
カスタマイズする場合
特定のコンポーネントのみを使用する場合は、require 'rails/all'
の代わりに必要なコンポーネントのみを個別に読み込むことができます:
# config/application.rb
require "rails"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
# 必要なコンポーネントのみを選択的に読み込む
注意点
不要なコンポーネントを読み込むと、アプリケーションの起動時間が長くなったり、メモリ使用量が増加する可能性があります。
strict_loadingとN+1問題対策
strict_loading とは
strict_loading
は、ActiveRecordの関連付け(アソシエーション)を遅延ロードする際に、明示的な事前ロード(eager loading)が行われていない場合に例外を発生させる機能です。これにより、意図しないN+1問題を開発段階で検出することができます。
基本的な使い方
# モデル全体で有効にする場合
class Person < ApplicationRecord
has_many :works, strict_loading: true
end
# 特定のクエリで有効にする場合
Person.strict_loading.find(1)
config.active_record.action_on_strict_loading_violation
Railsでは、strict_loading
違反が発生した際の動作を設定することができます。この設定はconfig/application.rb
またはconfig/environments/*.rb
で行います。
# config/application.rb
config.active_record.action_on_strict_loading_violation = :raise # デフォルト
# または
config.active_record.action_on_strict_loading_violation = :log # ログのみ出力
設定値の意味
-
:raise
: 例外を発生させます(デフォルト) -
:log
: ログに警告を出力するのみで、処理は継続します
実践的な使用例
1. 開発環境での設定
# config/environments/development.rb
config.active_record.action_on_strict_loading_violation = :raise
2. 本番環境での設定
# config/environments/production.rb
config.active_record.action_on_strict_loading_violation = :log
3. 特定のスコープでの使用
# 特定のスコープでのみstrict_loadingを有効にする
class Person < ApplicationRecord
scope :with_strict_loading, -> { strict_loading }
end
# 使用例
Person.with_strict_loading.find_each do |person|
person.works.each do |work| # ここでN+1が発生すると例外が発生
puts work.title
end
end
ベストプラクティス
- 開発環境では
:raise
を設定し、N+1問題を早期に発見 - 本番環境では
:log
を設定し、パフォーマンスに影響を与えないようにする - 必要な箇所でのみ
strict_loading
を使用し、過度な使用を避ける - パフォーマンスが重要なクエリでは、必ず
eager_load
やpreload
を使用する
rails consoleの効率的な開発環境設定
pry を使用しているので pry 用の設定になります
.pryrc ファイルを用意します
基本的な設定
Pry.config.pager = false
-- More -- のような表示がなくなり、全部表示されます。 Model.all のような場合も全部表示されますが、あまり全件を表示しないかつ、limit などで表示を絞れば良いかなと思い、自分はこのような設定をしています。
Rails固有の便利な設定
if defined?(Rails)
Pry.config.prompt = Pry::Prompt.new(
[
proc do |obj, nest_level, _|
prompt = ""
prompt += "#{Rails.version}@" if defined?(Rails.version)
prompt += "#{Rails.env.classify} "
prompt += "#{obj}"
prompt += "> "
end,
proc do |obj, nest_level, _|
"* "
end
]
)
# アプリケーションのルーティング一覧を表示
def routes
Rails.application.routes.routes.map do |route|
"#{route.verb.to_s.ljust(10)} #{route.path.spec.to_s.ljust(40)} #{route.defaults[:controller]}##{route.defaults[:action]}"
end.compact.each { |route| puts route }
end
# クエリの実行時間を計測
def benchmark_query(relation)
start_time = Time.now
result = relation.to_a
end_time = Time.now
puts "\n実行時間: #{end_time - start_time}秒"
puts "取得件数: #{result.size}件"
result
end
end
出力例
7.1.3@Development main>
のように表示され、local 環境で開発していることが分かりやすくなります。
7.1.3@Development main> routes
GET /xxxxx/xxxxx xxxxxx/xxxxxx/xxxxxx#new
.....
のように表示されます。 rails routes でも良いですが、console でも見ることができます。
relation = User.where(email: 'test@example.com')
D, [2025-04-18T08:55:57.676558 #1] DEBUG -- : User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'test@example.com'
=> []
[4] pry(main)>
[5] pry(main)> benchmark_query(relation)
D, [2025-04-18T08:56:07.871219 #1] DEBUG -- : User Load (1.4ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'test@example.com'
実行時間: 0.003148417秒
取得件数: 0件
=> []
のように表示されます。クエリ の実行時間を簡単に知ることができます。
まとめ
Railsアプリケーションを効率的に開発するためには、require 'rails/all'の理解と適切な設定、strict_loadingを活用したN+1問題の対策、そして rails console の効率的な活用が重要です。これらの機能を適切に使用することで、パフォーマンスの高い、保守性の良いアプリケーションを構築することができます。
We are hiring!
TAIANでは、このような開発・技術・思想に向き合い、未来をつくる仲間を一人でも多く探しています。少しでも興味を持っていただいた方は弊社の紹介ページをご覧ください。
Discussion