Don Giulio
Don Giulio

Reputation: 3284

rails set datetime db column to be the same value as updated_at

I'm generating a document from a model, this document always needs to match the lastest version of the model, and I can't recreate it every time I load it, because it's heavy and it's sent to docusign.

I figured I could use the updated_at field with and additional document_version:datetime db column, so that the model can be updated, but when appropriate I can check if updated_at == document_version and know if I need to reproduce the document.

in my code I have:

model.update(document_version: model.updated_at)

this doesn't work, I'm just setting the document version to the previous value of updated_at, the update method changes it.

model.update(document_version: model.updated_at, updated_at: model.updated_at)

the explicit setting of updated_at seems to be ignored.

my best option would be to update the document_version to whatever updated_at is going to be updated to.

I'm not sure how to do that

Upvotes: 1

Views: 862

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14900

I'm not sure this is the best way to do this, but to strictly answer the question, this is what you can do.

model.update_column(:document_version, model.updated_at)

or updating updated_at directly too

time = Time.current
model.update_columns(document_version: time, updated_at: time)

update_column does what it says, it only updates a single column without updating the updated_at column.

From the docs

This is the fastest way to update attributes because it goes straight to the database, but take into account that in consequence the regular update procedures are totally bypassed. In particular:

Validations are skipped.

Callbacks are skipped.

updated_at/updated_on are not updated.

Upvotes: 1

Related Questions