Updating ActiveRecord models without loading an instance using Postgresql
There're sometimes that we need to update an ActiveRecord Model but it is not necesary to load an instance, the normal flow would be the following:
profile = UserProfile.find_by(user_id: id)
profile.update(last_seen_at: Time.now)
The problem with this is that we load a useless instance of UserProfile, it is not needed, in a high traffic sites, an extra select query can count a lot, but luckly, Rails has addressed this with upsert
command:
UserProfile.upsert({ last_seen_at: Time.now, user_id: id }, unique_by: :user_id)
This will use native Postgresql upsert command to update a record if it exists or insert a new one and no select will be performed, everything in a single query instead of two.
To make it really work, you need to modify your created_at and updated_at columns to have default current_timestamp