【问题标题】:Is there a way to omit Active Record casting (from postgres ranges)?有没有办法省略 Active Record 转换(来自 postgres 范围)?
【发布时间】:2020-02-14 09:55:53
【问题描述】:

我有一个方法可以检查我的模型实例的日期交叉点。

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

假设我有预订r = Reservation.last

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

r.intersections

异常查询:

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

实际查询:

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')

架构:

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

我尝试了很多变体,但似乎演员隐藏在 Active Record 深处的某个地方。我可以为这个查询关闭它吗?

【问题讨论】:

  • @max AR 在查询中加上引号,所以它失败了。然而 AR::Attributes 工作得很好。我根据guide在模型中添加了attribute :daterange, range: true。谢谢! Сan你添加这个答案,我会标记它接受?

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

您可以使用 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">]>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-30
    • 2011-06-12
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多