【问题标题】:Just letting the user book ONE training hour per day只需让用户每天预订一个培训小时
【发布时间】:2017-03-23 22:05:33
【问题描述】:

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

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

用户模型:

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以像这样在您的视图中检查用户是否预订了培训:

    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
    

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

    希望这会有所帮助!

    【讨论】:

    • @Cesar 是的,代替:&lt;% if current_user.not_booked?(@training) %&gt;
    • 如果 current_user.trainings.any?: 没有路线匹配 {:action=>"show", :controller=>"bookings", :id=>nil, 它给了我以下错误, :training_id=>"6"} 缺少必需的键:[:id]
    • 我认为这是因为new_training_booking_path 需要培训和预订才能通过,而您只是通过了培训
    • 好吧,我不太明白,所以请解释一下我认为我理解的内容。而不是使用 我必须做 current_user.trainings.any ?,对于这种方法,我需要像这样 current_user.trainings.any?(@booking) 传递预订?
    • 我已经编辑了我的答案,以向您展示您需要做什么。希望对您有所帮助!
    猜你喜欢
    • 2017-08-01
    • 2017-08-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多