Rails - Sort by join table data

前端 未结 6 1878
庸人自扰
庸人自扰 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:33

    Another way to achieve this:

    scope :ordered, -> { includes(:availabilities).order(Availability.arel_table[:price]) }
    

    You can also specify ASC direction with

    scope :ordered, -> { includes(:availabilities).order(Availability.arel_table[:price].asc) }
    

    DESC:

    scope :ordered, -> { includes(:availabilities).order(Availability.arel_table[:price].desc) }
    

    Using arel_table on ActiveRecord model makes you save against scenario when table name changed (but it happens very rarely).

    Note that it is nice to add main_table#id for determinate sorting.

    So final version would be:

    scope :ordered, -> {
      includes(:availabilities).
        order(Availability.arel_table[:price].asc, order(Home.arel_table[:id].asc)
    }
    

提交回复
热议问题