Aaron
Aaron

Reputation: 14029

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.

Upvotes: 9

Views: 6141

Answers (2)

Dāvis Namsons
Dāvis Namsons

Reputation: 146

You can do it like this with arel:

User.where(User.arel_table[:created_at].eq(User.arel_table[:updated_at]))

Upvotes: 4

Ted
Ted

Reputation: 610

User.where("created_at = updated_at")

Upvotes: 18

Related Questions