问题
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
回答1:
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!
回答2:
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
回答3:
To avoid the thread_safe issue you could do this in the controller:
def business_params
params.require(:object).permit(:blah, :flop, :peep).merge(updated_by: current_user.id)
end
So every time your model saves it will update the updated_by field with the id of the current_user. Since setting created_by only happens once (in the create action) just set it there directly:
@business.created_by = current_user.id
Or store the user id in thread (ugly hack but is thread safe):
Thread.current[:user_id] = session[:current_user.id]
Ancient debate here which basically talks about how religiously you want to be about breaking MVC pattern and putting such logic in a model or not.
来源:https://stackoverflow.com/questions/35600045/automatically-update-created-by-and-updated-by-value-in-ruby-on-rails