ruby-on-rails - 覆盖 rails update_all 方法

标签 ruby-on-rails ruby-on-rails-3 activerecord

我需要重写 Rails(事件记录)update_all 方法,以便它也始终更新 updated_at 字段。我应该如何实现这一目标?

最佳答案

将以下代码放入文件/config/initializers/update_all_with_touch.rb

class ActiveRecord::Relation

  def update_all_with_touch(updates, conditions = nil, options = {})

    now = Time.now

    # Inject the 'updated_at' column into the updates
    case updates
      when Hash;   updates.merge!(updated_at: now)
      when String; updates += ", updated_at = '#{now.to_s(:db)}'"
      when Array;  updates[0] += ', updated_at = ?'; updates << now
    end

    update_all_without_touch(updates, conditions, options)
  end
  alias_method_chain :update_all, :touch

end

每当您使用 update_all 时,它会自动添加参数 :updated_at => Time.now

解释:

此代码段使用 alias_method_chain覆盖 update_all 的默认值:

alias_method_chain :update_all, :touch

方法update_all被我定义的方法update_all_with_touch替换,原来的update_all重命名为update_all_without_touch。新方法修改了upgrades对象注入(inject)updated_at的更新,接下来调用原来的update_all

关于ruby-on-rails - 覆盖 rails update_all 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076886/

相关文章:

ruby-on-rails - 无法在 Rails 控制台上填充测试 postgres 数据库

ruby-on-rails - 当 Rails 应该在幕后运行时,它会大声发布它的语法吗?

mysql - ruby ActiveRecord : Insert to parent and child tables in single commit

ruby-on-rails - 事件记录关联错误

ruby-on-rails - PG::InvalidParameterValue: 错误:参数 "client_min_messages"的无效值: "panic"

ruby-on-rails - 如何使用 Rails 和 Active Storage 实现 AWS S3 分段上传?

sql - 创建ActiveRecord中是否不存在功能?

ruby-on-rails - 如何在 Controller 内部使用 auto_link

ruby-on-rails - Rails has_many 通过表单,在连接模型中带有复选框和额外字段

ruby-on-rails - 使用来自请求 header 的 auth_token 而不是来自 Rails 3/devise 的 POST/PUT 参数