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
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With