Rails – Sort by join table data

I would suggest to avoid using default_scope, especially on something like price on another table. Every time you’ll use that table, join and ordering will take place, possibly giving strange results in complex queries and anyway making your query slower.

There’s nothing wrong with a scope of its own, it’s simpler and it’s even clearer, you can make it as simple as:

scope :ordered, -> { includes(:availabilities).order('availabilities.price') }

PS: Remember to add an index on price; Also see other great answers in here to decide between join/include.

Leave a Comment