【发布时间】:2025-12-27 11:15:06
【问题描述】:
我正在创建一个用户可以预订培训的应用程序。我做到了,当培训达到最大空位时,没有人可以再预订了。发生这种情况时,我试图显示错误,但错误没有出现,该方法有效,它不允许任何人参加培训,但应用程序需要告诉用户他无法预订,因为培训已满.
我想知道为什么错误没有显示以及如何修复它
预订模式:
class Booking < ApplicationRecord
belongs_to :user
belongs_to :training
validates :user_id, presence: true
validates :training_id, presence: true
validate :training_not_full?, on: :create
private
def training_not_full?
errors.add(:training, "Full training. Try another hour") unless training.can_book?
end
end
训练模型:
class Training < ApplicationRecord
has_many :users, through: :bookings
has_many :bookings
def can_book?
bookings.count < slots
end
end
显示训练视图:
<div class="row">
<section>
<h1>
HOUR: <%= @training.hour %>
</h1>
</section>
<section>
<h1>
SLOTS: <%= @training.left_slots %>
</h1>
</section>
<center>
<%= render 'bookings/booking_form' if logged_in? %>
<%= render 'bookings/index_bookings' if logged_in? %>
</center>
预订表单视图:
<%= form_for(@training) do |f| %>
<% if f.object.errors.any? %>
<% f.object.errors.full_messages.each do |full_message| %>
<p>
<%= full_message %>
</p>
<% end %>
<% end %>
<% unless current_user?(@user) %>
<% if current_user.not_booked?(@training) %>
<%= link_to "Book", new_training_booking_path(@training), class: "btn btn-primary" %>
<% else %>
<% @bookings.each do |booking| %>
<%= link_to "Unbook", training_booking_path(booking.training, booking), method: :delete, data: { confirm: 'Are you certain you want to delete this?' }, class: "btn btn-primary" %>
<% end %>
<% end %>
<% end %>
<% end %>
新的预订视图:
<h1>Book confirmation</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for ([@training, @booking]) do |f| %>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.hidden_field :training_id, value: "" %>
<%= f.submit "Confirm booking", class: "btn btn-primary" %>
<% end %>
【问题讨论】:
标签: ruby-on-rails ruby model-view-controller