训练满时不显示错误

时间:2017-03-12 18:00:21

标签: ruby-on-rails ruby model-view-controller

我创建了一个用户可以预订培训的apliccation。我做到了,当训练达到最大时段时,没有人可以预订了。我试图在发生这种情况时显示错误,但错误没有出现,方法有效,它不会让任何人参加培训,但应用程序需要告诉用户他不能预订,因为培训已满。

我想帮助知道为什么错误没有显示,我该如何解决?

预订模式:

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 %>

1 个答案:

答案 0 :(得分:1)

看起来在Rails 5中改变了add方法的实现。

请尝试

def training_not_full?
  errors.add(:training, :full, message: "Full training. Try another hour") unless training.can_book?
end

http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add

而不是

def training_not_full?
  errors.add(:training, "Full training. Try another hour") unless training.can_book?
end

http://api.rubyonrails.org/v4.2/classes/ActiveModel/Errors.html#method-i-add

请更改您的new.html.erb表单:

<%= form_for ([@training, @booking]) do |f| %>
  <% if f.object.errors.any? %>
    <% f.object.errors.full_messages.each do |full_message| %>
      <p>
        <%= full_message %>
      </p>
    <% end %>
  <% end %>
  <%= f.hidden_field :user_id, value: current_user.id %>
  <%= f.hidden_field :training_id, value: "" %>
  <%= f.submit "Confirmar reservacion", class: "btn btn-primary" %>
<% end %>