在Ruby on Rails中自动更新created_by和updated_by值 [英] Automatically update created_by and updated_by value in Ruby on Rails
问题描述
我正在尝试将当前 user_id
添加到 created_by
和 updated_by
字段。有人可以帮我吗?
I'm trying to add the current user_id
into a created_by
and updated_by
field automatically. Can anyone help me?
这里是数据模式:
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
推荐答案
首先, current_user
在您的控制器
中,没有任何直接的方法可以从模型
中获取数据。
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:
模型
class User < ActiveRecord::Base
cattr_accessor :current_user
# Your current code
end
应用程序控制器
class ApplicationController < ActionController::Base
before_action :set_current_user
def set_current_user
User.current_user = current_user if current_user
end
end
返回您的业务模型
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
因此,当用户
登录并执行任何操作,当前用户信息将设置为 User.current_user
,因此,如果业务
已创建或更新,将通过回调设置 current_user
信息。
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!
这篇关于在Ruby on Rails中自动更新created_by和updated_by值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!