LoginSignup
7
5

More than 5 years have passed since last update.

Ruby on Rails5でデータ更新者( userstamp, created_by, updated_by )を追加する方法

Last updated at Posted at 2018-11-14

Rails.version => "5.2.1"
RUBY_VERSION => "2.5.1"
deviseのset_current_user使用
しっくりくるgemが見当たらなかったのでハードコードで実装。

current_userがモデルから参照できなかったので、Userモデルのクラスメソッドに追加

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # ... その他色々

  before_action :set_current_user
  def set_current_user
    User.current_user = current_user if current_user
  end
end

データ更新前にcurrent_userを埋めるconcern。
user.idでも良いけど、user.emailの方がデータ追いやすいのでemailを埋めてる。

app/models/concerns/userstamps_concern.rb
module UserstampsConcern
  extend ActiveSupport::Concern

  included do
    before_create :update_created_by
    before_update :update_updated_by
  end

  def update_created_by
    self.created_by = current_user_email
    self.updated_by = current_user_email
  end

  def update_updated_by
    self.updated_by = current_user_email
  end

  def current_user_email
    User.current_user.try(:email) || 'system'
  end
end

Hogeモデルにcreated_by, updated_byを追加する場合

app/models/hoge.rb
class Hoge < ApplicationRecord
  include UserstampsConcern
  # ... その他色々
end

db/migrate/20181111111111_create_hoges.rb
class CreateHoges < ActiveRecord::Migration[5.2]
  def change
    create_table :hoges do |t|
        # ... その他色々
      t.timestamps
      t.string :created_by, null: false
      t.string :updated_by, null: false
    end
  end
end

やっつけで作ったので、改善箇所があれば教えてください。
データ更新者を埋めるのって、システム運用する上でマストな気がするんだけど、皆どうしてるの?

7
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
7
5