Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails activerecord query comparing two attributes of same record

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")
like image 875
Joe Avatar asked Jul 07 '12 18:07

Joe


1 Answers

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

like image 138
kddeisz Avatar answered Oct 23 '22 12:10

kddeisz