【问题标题】:Update Rails model without touching timestamp temporary更新 Rails 模型而不触及临时时间戳
【发布时间】:2015-10-02 21:09:52
【问题描述】:

我有一个Tweet 模型。我想更新模型属性但不更新时间戳。

我已经阅读/尝试了一些链接,但对我不起作用:

我试图通过在lib 目录中创建一个新文件active_record_base_patches.rb 来覆盖第二个链接中提到的ActiveRecord::Base。但是,引擎说在Tweet模型中找不到该方法。

所以,我尝试将 update_record_without_timestamping 移动到 Tweet 模型。现在找到了方法,但时间戳已更新。

有什么简单的方法可以暂时禁用 Rails 中的时间戳吗? Laravel 4 有这样的东西:https://stackoverflow.com/a/18906324/3427434.

PS:我在 Ruby 2.2.0 上使用 Ruby on Rails 4.2.3。

【问题讨论】:

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


    【解决方案1】:

    您可以在model/concern 中创建关注点,将其命名为model_timestamp.rb

    require 'active_support/concern'
    
    module ModelTimestamp
      extend ActiveSupport::Concern
    
      module ClassMethods
        def without_timestamps
          old = ActiveRecord::Base.record_timestamps
          ActiveRecord::Base.record_timestamps = false
          begin 
            yield 
          ensure
            ActiveRecord::Base.record_timestamps = old
          end
        end
      end
    end
    

    然后在您的模型中Tweet 添加include ModelTimestamp

    class Tweet < ActiveRecord::Base
      include ModelTimestamp
    
      ...
    end
    

    然后你想在哪里更新你的属性而不用timestamps来改变使用

    tweet = Tweet.last
    Tweet.without_timestamps do
      tweet.update(attributes)
    end
    

    【讨论】:

    • 我尝试了您的解决方案,但没有奏效。我注意到一个触发器:on update CURRENT_TIMESTAMP 在列中。删除触发器后,我再次尝试了您的解决方案,它现在可以工作了。
    猜你喜欢
    • 2014-05-21
    • 2013-09-25
    • 2018-12-27
    • 2015-08-30
    • 2014-09-30
    • 1970-01-01
    • 2011-02-20
    • 2018-11-17
    • 2017-06-06
    相关资源
    最近更新 更多