Ruby on rails Rails 3-使用2个型号和附加警告进行验证?

Ruby on rails Rails 3-使用2个型号和附加警告进行验证?,ruby-on-rails,model-view-controller,validation,Ruby On Rails,Model View Controller,Validation,我有两种型号: 讲课 招生 这个讲座有座席和等候名单。如果有讲座的报名,我想确认是否有免费座位 为此创建了两个帮助程序: def availableSeats return self.capacity - self.enrollments.confirmedEnrollments.count end def waitListAvailable return self.waitListCapacity - self.enrollments.waitList.count end 我

我有两种型号:

  • 讲课
  • 招生
这个讲座有座席和等候名单。如果有讲座的报名,我想确认是否有免费座位

为此创建了两个帮助程序:

def availableSeats
  return self.capacity - self.enrollments.confirmedEnrollments.count
end

def waitListAvailable
  return self.waitListCapacity - self.enrollments.waitList.count
end 
我想在注册控制器中进行检查,但它不起作用

if(@lecture.availableSeats <= 0)
  if(@lecture.waitListAvailable <= 0)
    flash[:error] = "Enrolment not possible as the waiting list is full."
    # interrupt and don't save, but how?
  else
    flash[:warning] = "You are on the waiting list."
    @enrollment.confirmed = nil
  end
else
  @enrollment.confirmed = DateTime.now
end

if(@touch.availableSeats我认为最好在模型中处理这个问题。我在之前提出的一个问题中也遇到过类似的问题


我假设您的注册模型定义了被录取的学生和等待名单上的学生。我还假设课堂模型有两个属性
可用的座位
可用的等待空间
,等待名单是先到先得的,如果名单满了,学生会被拒绝,但是实际座位由讲师手动确认或拒绝

我当然会建议不要在控制器级别做任何事情。这只是模型的工作

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :lecture

  validates_presence_of  :student_id, :lecture_id, :status
  validates_inclusion_of :status, :in => %w[waiting confirmed rejected]
  validate :must_fit_in_wait_list, :on => :create
  validate :must_fit_in_class,     :on => :update

  scope :waiting,   where(:status => 'waiting')
  scope :confirmed, where(:status => 'confirmed')
  scope :rejected,  where(:status => 'rejected')

  def must_fit_in_wait_list
    unless waiting.count < lecture.available_wait_space
      errors.add(:base, "The waiting list is full")
    end
  end

  def must_fit_in_class
    unless confirmed.count < lecture.available_seats
      errors.add(:status, "The seats are full")
    end
  end
end
班级注册%w[等待确认已拒绝]
验证:必须在等待列表中匹配,:on=>:创建
验证:必须在类中进行匹配,:on=>:更新
作用域:waiting,其中(:status=>“waiting”)
范围:已确认,其中(:status=>“已确认”)
作用域:已拒绝,其中(:status=>“已拒绝”)
def必须符合等待列表
除非waiting.count

顺便说一句,不要忘记在迁移过程中将
状态的默认值设置为“等待”。

谢谢edgerunner的回答!我找到了另一个简单的解决方案:

validate do |enrollment|
  if(enrollment.lecture.availableSeats <= 0)
    enrollment.errors.add_to_base("This lecture is booked out.") if enrollment.lecture.waitListAvailable <= 0
  end
end
if @enrollment.save
  if @enrollment.confirmed?
    format.html { redirect_to(@lecture, :notice => 'Enrollment successfull.') }
    format.xml  { render :xml => @lecture, :status => :created, :location => @lecture }
  else
    format.html { redirect_to(@lecture, :alert => 'You're on the waiting list!') }
    format.xml  { render :xml => @lecture, :status => :created, :location => @lecture }
  end