我正在尝试添加当前 user_id
成created_by
和 updated_by
场自动。谁能帮我?
这是数据模式:
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
在您的 controller
,没有任何直接的方法可以从 model
获取该数据。 .
我只是想一个这样的解决方案,欢迎任何建议:
型号
class User < ActiveRecord::Base
cattr_accessor :current_user
# Your current code
end
应用 Controller
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
登录并执行任何操作,当前用户信息将设置为User.current_user
,因此,如果 business
已创建或更新,即 current_user
info 将通过回调设置。我在这里想一个更好的解决方案,因为这不是线程安全的!
关于ruby-on-rails - 在 Ruby on Rails 中自动更新 created_by 和 updated_by 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35600045/