两种模型的活动记录过滤器

时间:2017-02-24 11:36:00

标签: ruby-on-rails rails-activerecord

我正在构建一个预订系统,用户可以在其中搜索开放预订。预订具有:范围,用于过滤在给定日期和时间预订的预订。仅在预订上的此过滤器工作正常,但我还想为给定seating_capacity(来宾)的表模型添加过滤器,以便我可以显示与给定seating_capacity匹配的所有预订预订给定的一天/时间。有关如何添加该过滤器的任何想法吗?

模型

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(guests, day, time)
    reserved_table_ids = Reservation.on(day, time).pluck('DISTINCT table_id')
    reserved_table_ids ? where.not(id: reserved_table_ids) : all
  end

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

控制器

class TablesController < ApplicationController
  def index
    @reserved_tables = Table.reserved_on(params[:guests], params[:day], params[:time])
    @open_tables = Table.free_on(params[:guests], 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 %>

模式

  create_table "reservations", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "table_id"
    t.datetime "date"
    t.time     "starts_at"
    t.time     "ends_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["table_id"], name: "index_reservations_on_table_id", using: :btree
    t.index ["user_id"], name: "index_reservations_on_user_id", using: :btree
  end

  create_table "tables", force: :cascade do |t|
    t.integer  "seating_capacity"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

4 个答案:

答案 0 :(得分:1)

您可以使用joins(:table)实现seat_capacity范围,它的外观如下:

scope :with, -> (capacity) { joins(:table).where(tables: {seating_capacity: capacity}) }

然后,您可以查询日期,时间和就座容量的特定预订,如下所示:

Reservations.on(day, time).with(capacity)

答案 1 :(得分:1)

Datagrid是在网页上轻松添加过滤器的好宝石。

https://github.com/bogdan/datagrid

结帐演示:http://datagrid.herokuapp.com/

答案 2 :(得分:0)

你需要使用join这里给出的好例子

rails scope and joins

答案 3 :(得分:0)

@reservationsWithinInterval1 = Reservation.where('startdate >= ? AND startdate < ? , @reservation.startdate, @reservation.enddate)

@reservationsWithinInterval2 = Reservation.where('enddate >= ? AND enddate < ?, @reservation.startdate, @reservation.enddate)

然后检查是否

  if @reservationsWithinInterval1.count > 0 || @reservationsWithinInterval2.count>0
  flash[:notice] = 'Select different time. Car already reserved in this time'