Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails query for two columns of the same table are equal to their values

I am trying to find if there exists a more Rails-y way to generate the following query

# The purpose of this query is to select Users who have not updated
# their user record.

SELECT `users`.* FROM `users` WHERE `users`.`created_at` = `users`.`updated_at`

I can accomplish it using Arel with the following:

arel_where = User.arel_table[:created_at].eq(User.arel_table[:updated_at])
User.where(arel_where)
  #=> … WHERE `users`.`created_at` = `users`.`updated_at`

However I cannot use any combination of the hash syntax to do this without accessing the table and using it's equality method. The following two fail due to turning the key into a string.

User.where(created_at: :updated_at)
  #=> … WHERE `users`.`created_at` = 'updated_at'

User.where(created_at: User.arel_table[:updated_at])
  #=> … WHERE `users`.`created_at` = '--- !ruby/struct:Arel::Attributes::Attribu…

Edit

While not a hard requirement I'm trying to avoid strings like the following:

User.where('created_at = updated_at')
  #=> WHERE (created_at = updated_at)

I sometimes analyze my logs and the difference in the query between this and the first which uses Arel would need to be accounted for.

like image 973
Aaron Avatar asked Nov 29 '17 16:11

Aaron


2 Answers

User.where("created_at = updated_at")

like image 114
Ted Avatar answered Nov 13 '22 10:11

Ted


You can do it like this with arel:

User.where(User.arel_table[:created_at].eq(User.arel_table[:updated_at]))
like image 20
Dāvis Namsons Avatar answered Nov 13 '22 10:11

Dāvis Namsons