如何在不触摸updated_at属性的情况下更新单个属性?

Kle*_* S. 44 ruby ruby-on-rails ruby-on-rails-3

我怎样才能做到这一点?

试图创建2个方法,称为

def disable_timestamps
  ActiveRecord::Base.record_timestamps = false
end

def enable_timestamps
  ActiveRecord::Base.record_timestamps = true
end
Run Code Online (Sandbox Code Playgroud)

和更新方法本身:

def increment_pagehit
  update_attribute(:pagehit, pagehit+1)
end
Run Code Online (Sandbox Code Playgroud)

使用回调来打开和关闭时间戳,例如:

before_update :disable_timestamps, :only => :increment_pagehit
after_update :enable_timestamps, :only => :increment_pagehit
Run Code Online (Sandbox Code Playgroud)

但它没有更新任何东西,甚至是所需的属性(pagehit).

有什么建议?我不想创建另一个表来计算分页数.

Nat*_*han 96

作为update_attributeIn Rails 3.1+ 的替代品,您可以使用update_column.

update_attribute跳过验证,但会触及updated_at并执行回调.

update_column跳过验证,不触摸updated_at,也不执行回调.

因此,update_column如果您不想影响updated_at并且不需要回调,那么这是一个很好的选择.

有关更多信息,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html.

另请注意,update_column将更新内存模型中属性的值,并且不会将其标记为脏.例如:

p = Person.new(:name => "Nathan")
p.save
p.update_column(:name, "Andrew")
p.name == "Andrew" # True
p.name_changed? # False
Run Code Online (Sandbox Code Playgroud)

  • 相似于`update_column`的Mongoid是`set`,如`person.set(:name,'Andrew')`.[Mongoid Docs - Atomic Persistence](http://mongoid.org/en/mongoid/docs/persistence.html#atomic) (2认同)

idl*_*ers 12

如果您只想增加一个计数器,我会使用该increment_counter方法:

ModelName.increment_counter :pagehit, id
Run Code Online (Sandbox Code Playgroud)

  • @克莱伯-S; increment_counter不会更改updated_at. (2认同)