Created
July 20, 2012 01:40
-
-
Save dnagir/3148131 to your computer and use it in GitHub Desktop.
Why squeel is great
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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