Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created July 20, 2012 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnagir/3148131 to your computer and use it in GitHub Desktop.
Save dnagir/3148131 to your computer and use it in GitHub Desktop.
Why squeel is great
# Example 1, not so cool (look at the 'less-than' and OR condition)
# plain AR:
Property.joins(:reservations).
where(status: 'reserved').
where("reservations.status = ? OR reservations.reservation_type = ?", 'active', 'offline').
where(reservations: {reservation_fee_received: false}).
where("reservations.fee_due_at < ?", DateTime.now)
# with squeel:
Property.joins{reservations}.
where{status == 'reserved'}.
where{(reservations.status == 'active') | (reservations.reservation_type == 'offline')}.
where{reservations.reservation_fee_received == false}.
where{reservations.fee_due_at < DateTime.now}
# Example 2: reusing queries
# plain AR
groups_with_this_property = PropertyGrouping.select(:id).joins(:properties).where(properties: {id: property.id})
allocations = company.received_allocations.joins(:allocation_items).
where("allocation_items.property_grouping_id IN (#{groups_with_this_property.to_sql })") # WTF!! Interpolation???
# Here I'd have to resort to Arel to do it properly
# with squeel
groups_with_this_property = PropertyGrouping.select{id}.joins{properties}.where{properties.id == my{property.id}}
allocations = company.received_allocations.joins{allocation_items}.
where{allocation_items.property_grouping_id.in groups_with_this_property}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment