2010-11-20 43 views
0

我有兩個型號:Rails 3 - 驗證2個模型和其他警告?

  • 講座
  • 招生

本次講座的容量和等候名單。如果有演講報名,我想驗證是否有免費座位。

創建了兩個幫手爲:

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 

任何想法如何工作?

回答

1

我假設你的入學模型定義都接受學生和那些在輪候名單上。我還假設講座模型有兩個屬性available_seatsavailable_wait_space,等待列表按先到先得的方式填充,如果列表已滿,學生將被拒絕,但實際座位由講師手動確認或拒絕。

我一定建議不要在控制器級別做任何事情。這僅適用於模型。

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 

順便說一句,不要忘記設置的默認值在你遷移到status「等待」。

0

謝謝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