我有一个非常简单的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
Attentings_count是一个计数器缓存列,其中包含为特定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实例已经达到容量的位置.
在这方面的任何帮助都将不胜感激.
Update个
我不确定在这种情况下这是否是执行乐观锁定的正确方式,但我是这样做的:
我在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模型上的计数器缓存列.以下是显示发生这种情况的位置的日志(log)输出-
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异常.在这一点上,如果尚未达到容量,整个过程将再次重试.
Update #2个
在@Kenn的响应之后,下面是SheuledRun对象上更新的Add方法:
# 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