2011-11-27 51 views
0

我正在爲預訂系統編程。 我希望我的用戶一次只能預訂一個(或定義數量的)資源。但是,我不想刪除我的數據庫的「過去」預留,因爲它將用於開票的目的。在預訂創建時,我需要驗證用戶未超過其預留配額,這意味着將來不會超過「配額」預訂。ruby​​驗證:基於時間限制一個對象的對象數量(has_many)

class User < ActiveRecord::Base 
    has_many :reservations 

    def active_reservations 
     #maybe worth to rewrite with a "find"? 
     my_list = [] 
     reservations.each do |reservation| 
     if (not reservation.past?) 
      my_list.push(reservation) 
     end 
     return my_list 
    end 

class Reservation < ActiveRecord::Base 
    belongs_to :user 
    validate :respect_user_quota 
    def past? 
     return (date < Date.now) 

    def respect_user_quota 
     if (user.active_reservations.count > user.quota) 
      errors.add(:user, "User quota exceeded!") 

這是實現此驗證的正確方法嗎?有什麼可能是錯的(我從來沒有看到錯誤信息)。配額驗證是否應該移至用戶類?

回答

1

我會嘗試做這個更簡單,並將驗證移動到用戶。

class User < ActiveRecord::Base 
    has_many :reservations 

    validate :reservation_quota 
    if sum(reservations.active) > quota # User.quota is implied here 
     errors.add(:user, "User quota exceeded!") 
    end 

class Reservation < ActiveRecord::Base 
    belongs_to :user 
    def active 
    active? 1 : 0 
    # If there's a boolean 'active' flag the ? method gets created automatically.  
    # This could be (reservation_date < Date.now)? ? 1 : 0 for you. 
    # Using `(expression)? ? true : false` is using the Ternary operator. 
    end 
end 
+0

最後,我徹底測試了它,我會更新用戶時,如果其保留的量太大的錯誤,但我想,當我創建一個新的預約......我應該添加到運行驗證在我的預約模型中提到,如果它導致用戶超出配額,就不能創建它? –