A solution for modifying operation conflicts in Rails applications at the same time. A rails Solution
Operating conflicts in Rails Applications are a common problem. Rails provides a simple and effective solution.
For example, there is a shop module in our system. An important part of the store is the management of product information. For example, operators often edit product information, including Product titles, marketing slogans, and prices. Because the changes are frequent and happen to be submitted and modified at the same time, there will be occasional problems with the loss of changes. Operator A changes the product title, and operator B changes the price, both A and B submit the modification and prompt that the modification is successful, but only the Modification result of A takes effect, and the modification of B is washed out by.
The reason is carefully studied and found that the modification function lacks the operation conflict mechanism, while the modification operation also causes problems. As shown in, A and B query data from the database at the same time, modify the same data on the web page, and submit and save the data based on the data submitted on the web page, as A result, the modification of A overwrites the modification of B.
Rails Optimistic lock Optimistic Locking is a powerful tool to solve this problem. Its principle is to add a field (lock_version by default, configurable) to the database table to record the version number of the data, each submitted modification carries this version number. Before the data is actually updated, determine whether the submitted lock_version data is consistent with the data in the database. If the data is inconsistent, it is considered that a data conflict occurs, the ActiveRecord: StaleObjectError exception will be thrown, so that the program can capture this exception and remind the user of a conflict. The user can coordinate and resolve the conflict.
The sample code is as follows:
Copy codeThe Code is as follows:
# Migration: add lock_version to products
Add_column: products,: lock_version,: integer, defalut: 0
# Update product with StaleObjectError checking
Begin
Product. update (params [: product])
Rescue ActiveRecord: StaleObjectError
Render 'filct'
End