Rails预订系统

时间:2017-02-23 03:51:09

标签: ruby-on-rails activerecord

我正在构建一个预订系统,用户可以在其中搜索开放预订。 :on范围会过滤给定日期和时间的预订,并创建一个reserved_table_ids数组。如果所选日期/时间有预订,则@reserved_tables@open_tables包含正确的表格ID。但是,如果在所选日期/时间内没有任何预订,则reserved_table_ids为空,@reserved_tables@open_tables为空。如果@open_tables为{null},有关如何将所有table_id铲入reserved_table_ids的任何想法都是空的吗?或者我应该考虑其他方法吗? (Rails 5.0.1)

型号:

class Reservation < ApplicationRecord
  belongs_to :user, optional: true
  belongs_to :table, optional: true

  scope :on, -> (day, time) { where('date = ? AND starts_at <= ? AND ends_at > ?', day, time, time)}
end

class Table < ApplicationRecord
  has_many :reservations
  has_many :users, through: :reservations

  def self.free_on(day, time)
    reserved_table_ids = Reservation.on(day, time).pluck('DISTINCT table_id')
    where.not(id: reserved_table_ids)
  end

  def self.reserved_on(day, time)
    reserved_table_ids = Reservation.on(day, time).pluck('DISTINCT table_id')
    where(id: reserved_table_ids)
  end
end

class User < ApplicationRecord
  has_many :reservations
  has_many :tables, through: :reservations
end

控制器:

class TablesController < ApplicationController
  def index
    @reserved_tables = Table.reserved_on(params[:day], params[:time])
    @open_tables = Table.free_on(params[:day], params[:time])
  end
end

查看:

<%= form_tag(tables_path, :method => "get", id: "table-search-form") do %>
  <%= text_field_tag :day, params[:day], class:"datepicker", placeholder: "Select Day" %>
  <%= text_field_tag :time, params[:time], class:"timepicker", placeholder: "Select Time" %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

1 个答案:

答案 0 :(得分:0)

当reserved_table_ids为空时似乎存在问题。你能尝试添加额外的条件吗?

def self.free_on(day, time)
  reserved_table_ids = Reservation.on(day, time).pluck('DISTINCT table_id')
  if reserved_table_ids
    where.not(id: reserved_table_ids)
  else
    all
  end
end

或者使用三元:

def self.free_on(day, time)
  reserved_table_ids = Reservation.on(day, time).pluck('DISTINCT table_id')
  reserved_table_ids ? where.not(id: reserved_table_ids) : all
end