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
?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With