我在寫預訂系統,它使用ice_cube寶石處理經常性預訂。 A Booking
has_many BookingItem
s,重複規則中每次出現一次,並且這些都是由Booking
的after_save回調調用的方法創建的。如何返回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
應用程序/視圖/預訂/ _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 %>
你目前如何嘗試顯示錯誤(你的表單代碼是什麼)? – cdesrosiers
我已經添加了表單代碼的相關位。我想我真正需要的是將'BookingItem's'錯誤添加到'@ booking'的某種方式。 – Simon