我正在编制预订系统。 我希望我的用户一次只能预订一个(或定义数量)的资源。但是,我不想删除"过去"保留我的数据库,因为它将用于开发票的目的。在创建预订时,我需要验证用户是否未超过其预留配额,这意味着不超过" quota"将来保留。
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!")
这是实施此验证的正确方法吗?可能有什么问题(我从未看到错误信息)。是否应将配额验证移至用户类?
答案 0 :(得分: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