如何有效地检查一组属性中的任何一个是否在before_save中发生了变化?

时间:2015-01-05 20:36:46

标签: ruby-on-rails

我想为类的一大组属性排除时间戳更新。许可时间戳更新集同样大,因此不需要在它们之间进行选择。

如何缩小以下内容?:

  def determine_timestamp_update
    if self.attr_1_changed?|| self.attr_2_changed? || ... || ... || ...
      self.class.record_timestamps = false
    else
      self.class.record_timestamps = true
    end
  end

1 个答案:

答案 0 :(得分:3)

以下是一种方法:

def determine_timestamp_update
  attrs = %w[ attr_1 attr_2 attr_3 ... ]

  self.class.record_timestamps = attrs.none? {|attr| changes[attr] }
end

已更改的changes方法returns a Hash属性。我们使用Enumerable#none?来检查每个给定的属性 - 如果false对于任何changes[attr]都是真实的,它将返回attrs