2017-02-23 55 views
0

我正在建立一個預訂系統,用戶可以在其中搜索公開預訂。 :on作用域篩選給定日期和時間的預定,並創建一個reserved_table_ids的數組。如果在選定的日期/時間有保留,則@reserved_tables@open_tables包含正確的表格ID。但是,如果在選定的日期/時間沒有任何預訂,則reserved_table_ids爲空,@reserved_tables@open_tables爲空。如果reserved_table_ids爲空,有關如何剷除所有table_id到@open_tables的任何想法?或者我應該考慮其他方法嗎? (滑軌5.0.1)Rails保留系統

型號:

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