Rails - Sort by join table data Rails - Sort by join table data ruby ruby

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.


Figured it out with help from this related post.

I moved the ordering out of the Home model and into the Availability model:

Availability

default_scope :order => "price ASC"

Then I eager loaded availabilities into the Home model and sorted by price:

Home

default_scope :include => :availabilities, :order => "availabilities.price ASC"


@ecoologic answer:

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

is great, but it should be mentioned that includes could, and in some cases should be replaced by joins. They both have their optimal use cases (see: #1, #2).

From practical standpoint there are two main differences:

  1. includes loads associated record(s); in this case Availability records. joins don't load any associated record(s). So you should use includes when you want to use data from join model e.g. display price somewhere. On the other hand, joins should be used if you intend to use join model's data only in query e.g. in ORDER BY or WHERE clauses.

  2. includes loads all records, while joins loads only those records that have associated join model. So in OP's case, Home.includes(:availabilities) would load all homes, while Home.joins(:availabilities) would load only those homes that have associated at least one availability.

Also see this question.