Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 745
Steve Davis Avatar asked Feb 08 '12 16:02

Steve Davis


Video Answer


2 Answers

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.

like image 161
ecoologic Avatar answered Sep 28 '22 13:09

ecoologic


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" 
like image 39
Steve Davis Avatar answered Sep 28 '22 13:09

Steve Davis