簡體   English   中英

如果將datetime列轉換為日期(rails),則not in失敗

[英]where not in fails if converting datetime columns to date (rails)

當我嘗試搜索特定日期未創建的記錄時,查詢中從datetime到date的轉換失敗

>> some_days = [Date.parse("2013-12-25"), Date.parse("2013-12-31")]
    => [Wed, 25 Dec 2013, Tue, 31 Dec 2013] 
>> User.where.not("DATE(created_at)" => some_days)

錯誤:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column users.DATE(created_at) does not exist

看來這不是正確的rails行為。 現在,我的解決方法是這樣,但是我想知道正確的方法。

>> User.where("DATE(created_at) not in (?)", some_days + [Date.new])

如果日期數組為空,則此解決方法不起作用,這就是為什么我將Date.new添加到它的原因。

簡單嘗試:

User.where.not(created_at: some_days)

這足夠聰明,可以處理空數組的情況(將where 1=1添加到語句中)

更新:

當我終於了解了問題所在時,有一個正確的解決方案。

class User
  scope :not_created_at, ->(dates) { where.not(created_at: Array.wrap(dates).map {|date| date..(date + 1.day)} ) }

end

User.not_created_at(some_days)

# Executed query
# SELECT "users".* FROM "users" WHERE (NOT ((("users"."created_at" BETWEEN '2013-12-25' AND '2013-12-26' OR "users"."created_at" BETWEEN '2013-12-31' AND '2014-01-01') OR 1=0)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM