Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically update created_by and updated_by value in Ruby on Rails

I'm trying to add the current user_id into a created_by and updated_by field automatically. Can anyone help me?

Here is data schema:

create_table "businesses", force: :cascade do |t|
  t.string "business_name"
  t.string "last_name"
  t.date "start_date"
  t.date "end_date"
  t.integer "created_by"
  t.integer "modified_by"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end
like image 704
Santi Avatar asked Jan 06 '23 14:01

Santi


2 Answers

First of all, current_user is in your controller, there isn't any directed way to get that data from model.

I just think a solution like this, welcome any recommendation:

Model

class User < ActiveRecord::Base
  cattr_accessor :current_user
  # Your current code
end

Application controller

class ApplicationController  < ActionController::Base
  before_action :set_current_user

  def set_current_user
    User.current_user = current_user if current_user
  end
end

Back to your Business model

class Business < ActiveRecord::Base
  # Your current code
  before_create :update_created_by
  before_update :update_modified_by

  def update_created_by
    self.created_by = current_user_id
  end

  def update_modified_by
    self.modified_by = current_user_id
  end

  def current_user_id
    User.current_user.try(:id)
  end
end

So, when user logged in and does any action, the current user information will be set to User.current_user, therefore, if a business was created or updated, that current_user info will be set via the callbacks.

I'm thinking a better solution here since this is not threadsafe!

like image 165
Hieu Pham Avatar answered Jan 30 '23 19:01

Hieu Pham


You can probably find a gem for that, but it will always involve some kind of manual intervention at some point.

Check the ruby toolbox: Gems for user stamping

like image 26
Marc Avatar answered Jan 30 '23 20:01

Marc