按日期范围验证票证

时间:2014-08-03 18:08:25

标签: ruby-on-rails ruby

我正在使用Ruby on Rails 4.1为我的示例项目创建一个票务预订应用程序。有三种模式 - 活动,门票和预订。活动有很多门票和预订。门票有很多预订,属于活动。预订属于活动和门票。

在故障单模型中,我使用以下模型更新故障单预订的状态:

class Ticket < ActiveRecord::Base
  belongs_to :event
  has_many :bookings

  before_create :check_start_date
  before_update :check_start_date


    def check_start_date
        if (self.booking_start_date >= DateTime.now) && (self.booking_end_date != DateTime.now)
            self.status = 'Open'
        else
            self.status = 'Closed'
        end
    end

    def maximum_tickets_allowed
        (1..maximum_quantity.to_i).to_a
    end

end

事件显示页面列出了故障单,用户可以通过单击“立即购买”按钮购买故障单。

<% @event.tickets.each do |ticket| %>
  <div class="row">
    <div class="col-md-10">
      <table class="table">
        <thead>
              <tr>
                  <th>Name</th>
                  <th>Price</th>
                  <th>Quantity</th>
                  <th>Status</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td><%= ticket.ticket_name %></td>
                  <td><%= number_to_currency(ticket.ticket_price) %></td>
                  <td><%= ticket.ticket_quantity %></td>
                  <td><%= ticket.status %></td>
                  <td><%= link_to "Buy Now", new_event_booking_path(@event, ticket_id: ticket.id), class: "btn btn-primary" %></td>
                  <td><%= link_to "Edit", edit_event_ticket_path(@event, ticket), class: "btn btn-link" %></td>
                  <td><%= link_to "Delete", event_ticket_path(@event, ticket), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-link" %></td>
          </tr>
      </table>
    </div>
    </div>
<% end %>

访客只能从此活动展示页面购买门票。其余页面被锁定。如何在状态结束时确保用户不允许购买门票?

1 个答案:

答案 0 :(得分:1)

How would I ensure that the user isn't allowed to buy tickets when the status is closed?

查看您的故障单型号,您已经在表格中显示了状态字段,因此只需在您的视图中检查它,或者不显示您的链接,或者您只需将其禁用即可。

<% if ticket.status == "open" %>
  <td><%= link_to "Buy Now", new_event_booking_path(@event, ticket_id: ticket.id), class: "btn btn-primary" %></td>
<% end %>

<td><%= link_to "Buy Now", new_event_booking_path(@event, ticket_id: ticket.id), class: "btn btn-primary", disabled: (ticket.status == "closed")  %></td> 

使用rails link_to_if helper

<%= link_to_if ticket.status == "open", 'Buy Now', new_event_booking_path(@event, ticket_id: ticket.id), class: "btn btn-primary" %>