ruby-on-railsrubyjoinhas-many-through

Rails - Sort by join table data


I've got a RoR project in the works. Here are the applicable sections of my models.

Home

has_many :communities, :through => :availabilities
has_many :availabilities, :order => "price ASC"

Community

has_many :homes, :through => :availabilities
has_many :availabilities

Availability

belongs_to :home
belongs_to :community

The "availabilities" table in the database has the additional data column "price"

So now I can call

@home.availabilities.each do |a|
  a.community.name
  a.price

and get back the availabilities data ordered by price as I want. My question is this:

Is there a way to automatically order Homes by avaliabilities.first.price (first = lowest)? Maybe something with default_scope :order?


Solution

  • 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') }
    

    I would call it price_ordered.

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