Date型のカラムの値が今日の日付より以前のレコードをとるのに苦戦した

発生した問題

Jobで以下のようにクライアントのidを取得している部分に対して、"今日の日付より以前の契約をしている"という条件も足したいと思いました。

client_ids = invoice_build.billing_closing_date.contracts.with_status(:actived).pluck(:client_id).uniq

これに where(“from > ?“, Date.today) を追加して以下のように書いたのですが、うまくクライアントidを取得できませんでした。。。

client_ids = @invoice_build.billing_closing_date.contracts.with_status(:actived).where( "from > ?",  Date.today ).pluck(:client_id).uniq

 

 

試したこと

コンソールでも似たような内容を試したのですが、以下のようなエラーが出てしまいました。。。

Contract.where('from < ?', Date.today).first

Contract Load (41.6ms) SELECT "contracts".* FROM "contracts" WHERE (from < '2019-04-24') ORDER BY "contracts"."id" ASC LIMIT $1 [["LIMIT", 1]]
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "from"
LINE 1: SELECT "contracts".* FROM "contracts" WHERE (from < '2019-0...
^
: SELECT "contracts".* FROM "contracts" WHERE (from < '2019-04-24') ORDER BY "contracts"."id" ASC LIMIT $1
from /Users/hayashiyoshino/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:614:in `async_exec'

 

以下のように、whereの条件をfromではなくcreated_atにするとうまく動いてくれるので書き方はあってそうな気がするのですが、fromに変えるとエラーとなっておりました。

Contract.where('created_at < ?', Date.today).first


fromカラムの型はdate型でしたので、以下のように比較するときちんとtrue返ってくれており、whereの時だけ比較できなくなってしまうみたいでした。。。

contract.from
=> Sat, 01 Dec 2018
[30] pry(main)> contract.from < Date.today
=> true

 

 

解決方法

テーブル名をつけることで、レコードを取得できるようになりました!!!

Contract.where("contracts.from < :from", from: Date.today).first
Contract Load (1.5ms) SELECT "contracts".* FROM "contracts" WHERE (contracts.from < '2019-04-24') ORDER BY "contracts"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> #<Contract:0x00007f8ffbdef138
id: 1,
client_id: 1036,
from: Sat, 01 Dec 2018,
>

 

 

感想その他

SQLの知識もActiveRecordの知識も足りていないので勉強してゆきます!!!

会社の先輩が貸してくれたSQLの本も読んでいこうと思います!!!