Jay
Jay

Reputation: 948

Rails order by two different associations

How can I sort from two different columns?

def order_by_percentage
  joins(:school_annual_data).order('school_annual_data.survey3_low_percent DESC')
  joins(:school_eligibility_data).order('school_eligibility_data.low_income_percent DESC')   
end 

if joins(:school_eligibility_data).order('school_eligibility_data.low_income_percent DESC') is nil, I want to sort by joins(:school_eligibility_data).order('school_eligibility_data.low_income_percent DESC')

Upvotes: 1

Views: 103

Answers (1)

Sonalkumar sute
Sonalkumar sute

Reputation: 2575

class YourModel
    scope :survey3, -> { where(survey3_low_percent: nil).reorder(low_income_percent: :desc) }
    scope :low, -> { where(low_income_percent: nil).reorder(survey3_low_percent: :desc) }

    def self.new_order
        survey3.to_a + low.to_a
    end
end

or

joins(:school_annual_data).order("COALESCE(school_annual_data.survey3_low_perce‌​nt, school_eligibility_data.low_income_percent)")

this will be like survey3_low_perce‌​nt || low_income_percent

Upvotes: 2

Related Questions