【问题标题】:activeModel::dirty records changes even when nothing changed即使没有任何变化,activeModel::dirty 记录也会发生变化
【发布时间】:2014-03-11 19:47:07
【问题描述】:

我正在使用 ActiveModel::Dirty 库。我有以下代码:

def tasks_changed?
   @changed = false
   self.tasks.each do |task|
     if task.previous_changes.any?
       @changed = true
       puts 'task changed so no update'
       puts 'this task changed' + task.inspect.to_s
       puts 'here are the changes' + task.previous_changes.to_s
     end
   end
   return @changed
end

如果用户更改表单中的某些内容,此方法会更改控制器的行为。问题是其中一个字段是日期时间,并且由于某种原因,previous_changes 认为日期时间每次都会更改,无论它是否已更改。

控制台甚至告诉我没有任何变化。以下是上述 puts 语句在控制台中产生的内容:

task changed so no update
this task changed#<Task id: 19, title: "task 1", content: "task 2 content", created_at: "2014-03-11 17:33:26", updated_at: "2014-03-11 20:00:01", schedule_id: 1, amount: nil, time_frame: "2014-03-27 20:00:00", state: "incomplete", denied: 0, order_number: 0, finished_description: nil>
here are the changes{"time_frame"=>[Thu, 27 Mar 2014 16:00:00 EDT -04:00, Thu, 27 Mar 2014 16:00:00 EDT -04:00], "updated_at"=>[Tue, 11 Mar 2014 15:57:44 EDT -04:00, Tue, 11 Mar 2014 16:00:01 EDT -04:00]}
task changed so no update
this task changed#<Task id: 21, title: "task 2", content: "task 2 content", created_at: "2014-03-11 17:42:18", updated_at: "2014-03-11 20:00:01", schedule_id: 1, amount: nil, time_frame: "2014-03-29 20:00:00", state: "incomplete", denied: 0, order_number: 1, finished_description: nil>
here are the changes{"time_frame"=>[Sat, 29 Mar 2014 16:00:00 EDT -04:00, Sat, 29 Mar 2014 16:00:00 EDT -04:00], "updated_at"=>[Tue, 11 Mar 2014 15:57:44 EDT -04:00, Tue, 11 Mar 2014 16:00:01 EDT -04:00]}
task changed so no update
this task changed#<Task id: 22, title: "task 3 ", content: "change", created_at: "2014-03-11 18:43:23", updated_at: "2014-03-11 20:00:01", schedule_id: 1, amount: nil, time_frame: "2014-03-31 20:00:00", state: "incomplete", denied: 0, order_number: 2, finished_description: nil>
here are the changes{"time_frame"=>[Mon, 31 Mar 2014 16:00:00 EDT -04:00, Mon, 31 Mar 2014 16:00:00 EDT -04:00], "updated_at"=>[Tue, 11 Mar 2014 15:57:44 EDT -04:00, Tue, 11 Mar 2014 16:00:01 EDT -04:00]}

我的基本问题是为什么 previous_changes 每次都认为有变化,我该如何解决?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord activemodel active-model-serializers


    【解决方案1】:

    至少timeframeupdated_at 发生了变化。请注意,时间对象不仅仅包含秒数,而且 inspect 方法不显示例如毫秒。

    但是如果不提供执行此操作的代码,没有人能够告诉您为什么会发生这种情况。

    【讨论】:

    • 执行此操作的代码是什么意思?我提供了所有涉及脏关联的代码?
    • 我的意思是之前处理tasks 的所有代码。您检查更改,因此必须有可能更改它们的代码。也许有关联对象的回调,有些东西触及了属性,也许是规范化器,或者你用几乎相同的值覆盖了 Web 表单的值。我不知道...
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2016-10-09
    • 2015-02-16
    • 2021-12-21
    • 1970-01-01
    • 2019-10-28
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多