Ruby on rails Rails-按日期范围筛选,共有2个型号
我有两种型号:空间和预订。空间有很多预订,预订有两个日期属性:签入和签出 给定一个有效的日期范围,我想显示该范围内的所有可用空间 这是一种观点:Ruby on rails Rails-按日期范围筛选,共有2个型号,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我有两种型号:空间和预订。空间有很多预订,预订有两个日期属性:签入和签出 给定一个有效的日期范围,我想显示该范围内的所有可用空间 这是一种观点: <%= form_tag spaces_path, method: :get do %> <%= date_field_tag :query1, params[:query1], class: "form-control" %> <%= dat
<%= form_tag spaces_path, method: :get do %>
<%= date_field_tag :query1,
params[:query1],
class: "form-control" %>
<%= date_field_tag :query2,
params[:query2],
class: "form-control" %>
<%= submit_tag "Search", class: "btn" %>
<% end %>
我假设问题的根本原因是我将活动记录查询对象
视为哈希数组,不确定它是否正确。我对此做了一些研究,但没有找到任何详尽的答案。使用SQL子查询(例如在PostgreSQL中),您可以这样做:
sql=我将首先向Booking
模型添加一个范围:
# in app/models/booking.rb
scope :overlapping, ->(from, to) {
where(
"(check_in, check_out) OVERLAPS (?, ?)", from, to
)
}
然后将整个控制器方法更改为:
def index
@spaces = Space.all
if params[:query1].present? && params[:query2].present?
from = DateTime.parse(params[:query1])
to = DateTime.parse(params[:query2])
@space = @space.where.not(
id: Booking.select(:space_id).overlapping(from, to)
)
end
end
def index
@spaces = Space.all
if params[:query1].present? && params[:query2].present?
from = DateTime.parse(params[:query1])
to = DateTime.parse(params[:query2])
@space = @space.where.not(
id: Booking.select(:space_id).overlapping(from, to)
)
end
end