class AddLockVersionToArticles < ActiveRecord::Migration[6.1]
def change
add_column :articles, :lock_version, :integer, null: false, default: 0
end
end
class Admin::ArticlesController < ApplicationController
def update
article = Article.find(params[:id])
article.update!(article_params)
redirect_to [:admin, article]
rescue ActiveRecord::StaleObjectError
redirect_to [:admin, article], alert: 'This article was updated by someone else. Please reload and try again.'
end
private
def article_params
params.require(:article).permit(:title, :body, :lock_version)
end
end
If multiple admins edit the same record, use lock_version. Rails will raise on conflicting updates, and you can show a friendly “this changed underneath you” message. It prevents subtle lost updates.