Her web uygulaması için performans kritiktir. Ruby on Rails uygulamanızı optimize etmek için temel ipuçları:
1. Veritabanı Sorgu Optimizasyonu#
N+1 Sorgu Problemini Önlemek için Includes Kullanın#
1
2
3
4
5
6
7
8
9
10
11
12
| {title="app/controllers/users_controller.rb" hl_lines=[8]}
# Kötü - N+1 sorgu problemi
users = User.all
users.each do |user|
puts user.posts.count
end
# İyi - Includes kullanın
users = User.includes(:posts) # Bu satır N+1 sorgu problemini önler
users.each do |user|
puts user.posts.count
end
|
Veritabanı İndekslerini Kullanın#
1
2
3
4
5
6
7
| # Migration dosyanızda
class AddIndexToUsers < ActiveRecord::Migration[7.0]
def change
add_index :users, :email
add_index :posts, [:user_id, :created_at]
end
end
|
2. Önbellekleme Stratejileri#
Fragment Önbellekleme#
1
2
3
4
5
6
7
| <!-- View dosyanızda -->
<% cache(post, expires_in: 1.hour) do %>
<div class="post">
<h2><%= post.title %></h2>
<p><%= post.content %></p>
</div>
<% end %>
|
Action Önbellekleme#
1
2
3
4
5
6
7
| class PostsController < ApplicationController
caches_action :index, expires_in: 1.hour
def index
@posts = Post.published.includes(:author)
end
end
|
3. Arka Plan İşleri#
Ağır işlemler için arka plan işlerini kullanın:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| # Job sınıfı
class EmailNotificationJob < ApplicationJob
queue_as :default
def perform(user_id)
user = User.find(user_id)
UserMailer.welcome_email(user).deliver_now
end
end
# Controller'ınızda
def create
@user = User.new(user_params)
if @user.save
EmailNotificationJob.perform_later(@user.id)
redirect_to @user
end
end
|
Sonuç#
Bu optimizasyon teknikleri Rails uygulamanızın performansını önemli ölçüde iyileştirebilir. Değişikliklerin etkili olduğundan emin olmak için önce ve sonra ölçümler yapmayı unutmayın.