2017-02-23 56 views
0

Я создаю систему бронирования, где пользователи могут искать открытую резервацию. Область :on фильтрует резервирование, которое присутствует в данный день и время, и создаю массив из reserved_table_ids. Если в выбранный день/время есть оговорки, @reserved_tables и @open_tables содержат правильные идентификаторы таблицы. Однако, если в выбранный день/время нет каких-либо оговорок, reserved_table_ids имеет значение null и @reserved_tables и @open_tables не заполнены. Любые идеи о том, как выкопать все table_ids в @open_tables, если reserved_table_ids null? Или есть другие подходы, которые я должен рассмотреть? (Rails 5.0.1)Rails Reservation System

Модели:

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

ответ

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 
+0

Я думал условно тоже, но мне нравится ваше трехкомпонентное решение, потому что она чище. Благодаря! – rymcmahon