只需让用户每天预订一个训练小时

时间:2017-03-23 22:05:34

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

我创建了一个用户可以预订一小时培训的应用程序。该应用程序已经完成,但是用户可以同时在多个培训时间内预订错误。

如果用户已经预订,我想这样做,书籍按钮在其他培训中消失(如果他参加培训,他已经预订了unbook按钮将会出现)。我想请求帮助来完成这项工作。我的代码如下:

用户模型:

class User < ApplicationRecord

  has_many :trainings, through: :bookings
  has_many :bookings


  def not_booked?(training)
    bookings.where(training: training).none?
  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>

booking_form查看:

<% unless current_user?(@user) %>
  <% if current_user.not_booked?(@training) %>
    <%= link_to "Book", new_training_booking_path(@training),
        class: "btn btn-primary" %>
  <% else %>
    <%= link_to "Unbook",
        training_booking_path(@training, @training.bookings.where(user: current_user).first),
        method: :delete, data:{ confirm: 'Sure?' },
        class: "btn btn-primary" %>
  <% end %>
<% end %>

为了记录,每天午夜都会删除预订,所以我需要的只是正确的代码,让用户只需预订一次(如果他被预订,不要让他在另一个小时内预订)

由于

1 个答案:

答案 0 :(得分:0)

您可以检查用户是否已在您的观看中预订了培训,如下所示:

if current_user.trainings.any? # user booked any training hours?
  if current_user.trainings.include?(@training)
   # user already booked this training hour
   <%= link_to "Unbook",
      training_booking_path(@training, @training.bookings.where(user: 
      current_user).first),
      method: :delete, data:{ confirm: 'Sure?' },
      class: "btn btn-primary" %>
  end 
else
  # user hasn't booked any training hours 
  <%= link_to "Book", new_training_booking_path(@training, @booking,
    class: "btn btn-primary" %> 
end

首先,检查用户是否有任何培训时间;如果他有,你检查他是否已经预订了当前的培训并显示取消预订按钮,但如果他没有,则显示预订按钮。

希望这有帮助!