Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

ruby - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...