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…
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.
User.where("created_at = updated_at")
You can do it like this with arel:
User.where(User.arel_table[:created_at].eq(User.arel_table[:updated_at]))
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