我有一个非常简单的 Rails 应用程序,它允许用户注册他们参加一组课程的情况。ActiveRecord 模型如下:
class Course < ActiveRecord::Base
has_many :scheduled_runs
...
end
class ScheduledRun < ActiveRecord::Base
belongs_to :course
has_many :attendances
has_many :attendees, :through => :attendances
...
end
class Attendance < ActiveRecord::Base
belongs_to :user
belongs_to :scheduled_run, :counter_cache => true
...
end
class User < ActiveRecord::Base
has_many :attendances
has_many :registered_courses, :through => :attendances, :source => :scheduled_run
end
ScheduledRun 实例的可用名额有限,一旦达到限制,就不能再接受出席。
def full?
attendances_count == capacity
end
出勤计数是一个计数器缓存列,保存为特定 ScheduledRun 记录创建的出勤关联的数量。
我的问题是我不完全知道正确的方法来确保当一个或多个人同时尝试注册课程的最后一个可用位置时不会发生竞争情况。
我的考勤控制器如下所示:
class AttendancesController < ApplicationController
before_filter :load_scheduled_run
before_filter :load_user, :only => :create
def new
@user = User.new
end
def create
unless @user.valid?
render :action => 'new'
end
@attendance = @user.attendances.build(:scheduled_run_id => params[:scheduled_run_id])
if @attendance.save
flash[:notice] = "Successfully created attendance."
redirect_to root_url
else
render :action => 'new'
end
end
protected
def load_scheduled_run
@run = ScheduledRun.find(params[:scheduled_run_id])
end
def load_user
@user = User.create_new_or_load_existing(params[:user])
end
end
如您所见,它没有考虑 ScheduledRun 实例已经达到容量的位置。
对此的任何帮助将不胜感激。
更新
我不确定这是否是在这种情况下执行乐观锁定的正确方法,但这是我所做的:
我在 ScheduledRuns 表中添加了两列 -
t.integer :attendances_count, :default => 0
t.integer :lock_version, :default => 0
我还向 ScheduledRun 模型添加了一个方法:
def attend(user)
attendance = self.attendances.build(:user_id => user.id)
attendance.save
rescue ActiveRecord::StaleObjectError
self.reload!
retry unless full?
end
保存出勤模型后,ActiveRecord 继续更新 ScheduledRun 模型上的计数器缓存列。这是显示发生这种情况的日志输出 -
ScheduledRun Load (0.2ms) SELECT * FROM `scheduled_runs` WHERE (`scheduled_runs`.`id` = 113338481) ORDER BY date DESC
Attendance Create (0.2ms) INSERT INTO `attendances` (`created_at`, `scheduled_run_id`, `updated_at`, `user_id`) VALUES('2010-06-15 10:16:43', 113338481, '2010-06-15 10:16:43', 350162832)
ScheduledRun Update (0.2ms) UPDATE `scheduled_runs` SET `lock_version` = COALESCE(`lock_version`, 0) + 1, `attendances_count` = COALESCE(`attendances_count`, 0) + 1 WHERE (`id` = 113338481)
如果在保存新的出勤模型之前对 ScheduledRun 模型进行了后续更新,这应该会触发 StaleObjectError 异常。此时,如果尚未达到容量,则将再次重试整个过程。
更新#2
继@kenn 的回复之后,这里更新了 SheduledRun 对象上的参加方法:
# creates a new attendee on a course
def attend(user)
ScheduledRun.transaction do
begin
attendance = self.attendances.build(:user_id => user.id)
self.touch # force parent object to update its lock version
attendance.save # as child object creation in hm association skips locking mechanism
rescue ActiveRecord::StaleObjectError
self.reload!
retry unless full?
end
end
end