ActiveRecord touch (: column) always also updates: updated_at

I have the same problem as this guy: http://www.ruby-forum.com/topic/197440 .

I try to touch column ( :touched_at) without automatic updating :updated_at, but when viewing SQL queries, it always updates to the current time.

I thought that this could be due to the specific model in which I used it, so I tried a couple of different ones with the same result.

Does anyone know what can make it always set :updated_atwhen touching another column? touchuses write_attributeinternally, so he should not do this.

Edit:

Some clarifications ... in the Rails 2.3.5 docs it touchstates that "If the attribute name is passed, this attribute is used to touch instead of the updated_at / on attributes." But mine doesn’t act like that. Perhaps this is the case when the documents deviated from the actual state of the code?

+3
source share
1 answer

You really want to write your own SQL:

def touch!
  self.class.update_all({:touched_at => Time.now.utc}, {:id => self.id})
end

This will generate this SQL:

UPDATE posts SET touched_at = '2010-01-01 00:00:00.0000' WHERE id = 1

This is what you need. If you call #save, this will call # create_with_timestamps or # update_with_timestamps , and this is what updates the updated_on / updated_at / created_on / created_at columns updates.

By the way, the # touch source says it all.

+8

Source: https://habr.com/ru/post/1766104/


All Articles