我正在编写一个使用ice_cube gem 处理定期预订的预订系统。一个Booking
has_many BookingItem
s,一个用于重复规则中的每次出现,这些是在一个由Booking
的 after_save 回调调用的方法中创建的。
这一切都很好,直到我添加了一个验证,通过检查在给定的时间BookingItem
还没有一个来避免重复预订。BookingItem
此验证引发了一个错误,我想在预订表单上显示该错误,但目前它只是默默地阻止Booking
保存 - 因为错误是由它引发的,BookingItem
它没有被传递回Booking
.
应用程序/模型/booking.rb
class Booking < ActiveRecord::Base
include IceCube
has_many :booking_items, :dependent => :destroy
after_save :recreate_booking_items!
# snip
private
def recreate_booking_items!
schedule.all_occurrences.each do |date|
booking_items.create!(space: self.requested_space,
booking_date: date.to_date,
start_time: Time.parse("#{date.to_date.to_default_s} #{self.start_time.strftime('%H:%M:00')}"),
end_time: Time.parse("#{date.to_date.to_default_s} #{self.end_time.strftime('%H:%M:00')}"))
end
end
end
应用程序/模型/booking_item.rb
class BookingItem < ActiveRecord::Base
belongs_to :booking
validate :availability_of_space
# snip
private
def availability_of_space
unless space.available_between? DateTime.parse("#{booking_date}##{start_time}"), DateTime.parse("#{booking_date}##{end_time}")
errors[:base] << "The selected space is not available between those times."
end
end
end
app/views/booking/_form.html.erb
<% if @booking.errors.any? %>
<div id="error_explanation">
<p><%= pluralize(@booking.errors.count, "error") %> prohibited this booking from being saved:</p>
<ul>
<% @booking.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form_for(@booking, :html => { :class => "nice custom"}) do |f| %>
...
<% end %>