Aron Latis
Aron Latis

Reputation: 38

Modify updated_at attribute through db trigger in rails

I was wondering if there is anything wrong about updating the updated_at attribute of a record through a db trigger in terms of fragment caching (i.e. the partials dont get re-cached / the old cache keys do not disappear from memory).

additional info I'm using a trigger due to using the upsert gem which does not modify the updated_at attribute unless explicitly told to do so ( which I do not want to do ); also, due to the same gem I cannot use an active::record after_save or before_save on the model.

Please let me know if there any other information I should provide to add some clarity to my question.

Upvotes: 1

Views: 394

Answers (2)

Alexey Zalyotov
Alexey Zalyotov

Reputation: 474

One more way to achive that is to use on_duplicate attribute of the Rails upsert_all method (without any gems). Check the documentation, pseudo code example:

YourModel.upsert_all(
  array_of_data,
  unique_by: %i[field_1 field_2],
  on_duplicate: Arel.sql('updated_at = current_timestamp')
)

If you have other fields to update, don't forget to add them into Arel.sql:

on_duplicate: Arel.sql('updated_at = current_timestamp, field_to_update = excluded.field_to_update')

Upvotes: 1

Vi.
Vi.

Reputation: 1012

There isn't nothing wrong, but if you need to do so you can simply use record.touch in a method so your code will be more clean and app will be more maintainable.

Upvotes: 1

Related Questions