Returning unique records from an ActiveRecord query
Having recently upgraded a legacy Rails project from 3.x to 4.2.x, one of the biggest benefits is that I can finally use some nice additions to
ActiveRecord. One of my favorites is
#distinct, which, as the name says, will return
DISTINCT records for a query.
Let's look at an example:
Say we have a bunch of orders, where each one can contain multiple transactions. Now we want to show all orders with a transaction that is in
state "declined". How would we do this?
It's actually really simple:
As easy as that. No hand-written SQL statements, no sub-queries, no memory intensive iterating-over-an-array.
If you haven't yet seen the super-useful
merge method, be sure to checkout the Rails API documentation.