Raju akula
Raju akula

Reputation: 1305

How to avoid multiple users page acess at same time and same record in rails?

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

Answers (1)

kiddorails
kiddorails

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:

  1. First comes on /edit page, set product.edited_by to that user.
  2. Second user visits /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.
  3. Remove the edited_by when user has updated the record.

But this comes at cost. There are lot of corner cases around this:

  1. User might come on edit page and acquire edited_by association. But never update the record (thus never giving another user to update the product)
  2. In case of some logic exception, edited_by might never be reset.
  3. Involves devising a strategy when to reset if case #1 occurs.

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

Related Questions