简体   繁体   English

有没有办法省略 Active Record 转换(来自 postgres 范围)?

[英]Is there a way to omit Active Record casting (from postgres ranges)?

I have a method that checks the date intersections for my model instance.我有一个方法可以检查我的模型实例的日期交叉点。

def intersections
  Reservation.where("daterange && ?", self.daterange)
end

Suppose I have the reservation r = Reservation.last假设我有预订r = Reservation.last

=> #<Reservation id: 3, home_id: 1, daterange: Sun, 10 Feb 2020...Fri, 21 Feb 2020>

r.intersections

Excepted query:异常查询:

SELECT "reservations".* FROM "reservations" WHERE (daterange && '[2020-02-10,2020-02-21)')

Actual query:实际查询:

SELECT "reservations".* FROM "reservations" WHERE (daterange && '2020-02-10','2020-02-11','2020-02-12','2020-02-13','2020-02-14','2020-02-15','2020-02-16','2020-02-17','2020-02-18','2020-02-19','2020-02-20')

schema:架构:

create_table "reservations", force: :cascade do |t|
  ...
  t.daterange "daterange"
end

I tried a lot of variations but it seems that the casting is hidden somewhere deep inside Active Record.我尝试了很多变体,但似乎演员表隐藏在 Active Record 深处的某个地方。 Can I just turn it off for this query?我可以为此查询关闭它吗?

You can use the Attributes API to setup casting.您可以使用 Attributes API 来设置转换。

class Reservation < ApplicationRecord
  attribute :daterange, range: true

  def intersections
    Reservation.where(
      "daterange && ?", self.daterange
    )
  end
end
irb(main):026:0> Reservation.first.intersections
  Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" ORDER BY "reservations"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" WHERE (daterange && '[2020-02-14,2020-02-16)') LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Reservation id: 1, daterange: "[2020-02-14,2020-02-16)", created_at: "2020-02-14 11:13:13", updated_at: "2020-02-14 11:13:13">, #<Reservation id: 2, daterange: "(,)", created_at: "2020-02-14 11:33:16", updated_at: "2020-02-14 11:33:16">]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM