简体   繁体   中英

ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: timestamp without time zone >= integer

I'm having trouble comparing dates in my rails 2 project. In one of my queries, one of the conditions is this:

:conditions => ["bills.created_at >= #{beginning.to_s.delete("-")} AND bills.created_at <= #{ending.to_s.delete("-")}"]

I pass it "2013-10-16" and "2013-12-15" for beginning and ending respectively. This worked in my staging environment but is broken in my production environment:

    ActiveRecord::StatementInvalid: PGError: ERROR:  operator does not exist: timestamp without time zone >= integer
    LINE 1: SELECT * FROM "bills" WHERE (created_at >= 20131016)

How would I fix this? I saw this heroku Postgres error - operator does not exist timestamp without timezone = integer but it didn't help.

Your query is definitely very far from an ActiveRecord query syntax. Assuming you are using at least Rails 3 and beginning and ending are Time objects:

Bill.where("created_at >= ? AND created_at <= ?", beginning, ending)

or you can also use BETWEEN passing a Ruby Range

Bill.where(created_at: beginning..ending)

Please avoid to interpolate values in the query like you just did. The resulting query it's not protected against SQL injection.

You may also want to review the ActiveRecord documentation to learn a little bit how to use it properly.

For Rails < 3 you should pass the conditions to the find method.

Bill.find(:all, :conditions => "created_at >= ? AND created_at <= ?", beginning, ending)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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