Reputation: 1305
Would like to display a message when click any product edit page if somebody already opened/in that same record/page.
how to track users access on edit action for same record?ultimately i want to display message as "somebody already editing this product" to avoid overwrite process between multiple users.
please share your ideas on it.
Upvotes: 1
Views: 1364
Reputation: 13014
Naive solution for this might be adding an association say:
class Product < ActiveRecord::Base
belongs_to :edited_by, class_name: 'User', foreign_key: 'edited_by_user_id'
end
class User < ActiveRecord::Base
has_many :edits, class_name: 'Product', foreign_key: 'edited_by_user_id'
end
and then:
/edit
page, set product.edited_by
to that user./edit
page. You can check if edited_by
for that product is set, then show him the message; blocking him to update the same product.edited_by
when user has updated the record.But this comes at cost. There are lot of corner cases around this:
edited_by
association. But never update the record (thus never giving another user to update the product)edited_by
might never be reset.Thus, I advise using Optimistic Locking instead. You can add a migration with :lock_version
for your Product model. This will prevent the stale object from ever being saved in this scenario, preventing such conflicts.
It will raise the exception ActiveRecord::StaleObjectError
when User #2(or first) tries to update an old record, which you can use to show your custom message by handling that exeption.
Hope that helps :)
Upvotes: 2