Rails - Sort by join table data

前端 未结 6 1879
庸人自扰
庸人自扰 2020-12-05 07:03

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

Home

has_many :communities, :through => :ava         


        
6条回答
  •  囚心锁ツ
    2020-12-05 07:20

    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.

提交回复
热议问题