I am looking for a way to build a query that compares two attributes of the same record, without first pulling the record and comparing post-query. My specific case would potentially have 10k's of records, so iterating through each is not an option.
Example: Finding this record by querying .where updated_at == created_at
#<User id: 1, name: "xxx", created_at: "2012-07-01 12:00:00", updated_at: "2012-07-01 12:00:00">
Rails 3+, ActiveRecord, MySQL.
Update: As commentor Matzi points out, the following is valid when using sqlite, but not mysql:
User.where("created_at == updated_at")
Solved: Simple mistake, ruby vs sql.
Sqlite can use:
User.where("created_at == updated_at")
but MySQL requires:
User.where("created_at = updated_at")
If you want to do this in a generic way, you should use ARel to get away from a specific database implementation. Something like
users = User.arel_table
User.where(users[:created_at].eq(users[:updated_at]))
would work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With