ruby-on-rails - 在 Ruby on Rails 中自动更新 created_by 和 updated_by 值

标签 ruby-on-rails ruby-on-rails-4 activerecord

我正在尝试添加当前 user_idcreated_byupdated_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/

相关文章:

css - Rails Assets 管道 : compressed/minified CSS loaded but not styling document

ruby-on-rails-4 - 如何在 Rails 中创建和使用像 current_user (devise) 这样的全局变量?

sql - rails-5 activerecord postgresql-9.6 enable_neSTLoop 用于单个 sql 查询

ruby-on-rails - 规范不同的数据库

ruby-on-rails - 通过关系创建 has_many 的问题 (Rails 4)

mysql - Rails 4.2.7 mysql 设置两个自定义主键

ruby-on-rails - Rails 迁移 -- rake db :status says migration is down, 但数据库已经迁移?

ruby-on-rails - mocha/rspec 有 "not_expects"吗?

ruby-on-rails - 遇到错误 "couldn' t find file 'ckeditor/override' "在我的 application.js 文件中的问题

ruby-on-rails - 索引显示顺序