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)
idl*_*ers 12
如果您只想增加一个计数器,我会使用该increment_counter方法:
ModelName.increment_counter :pagehit, id
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33255 次 |
| 最近记录: |