2016-09-27 69 views
1

我有一個模型內的下列範圍:範圍變更哈希語法

class Office < ApplicationRecord 
    belongs_to :money_pot 
    has_one :fiscal_year, through: :money_pot 
    has_one :money_type, through: :money_pot 

    scope :order_by_fiscal_year_and_money_type, -> { 
     joins(money_pot: [:fiscal_year, :money_type]) 
     .order("fiscal_years.end_date desc, money_types.short_name")} 
end 

這個範圍確實工作。但是,我想從order子句中的「純字符串」語法切換到「散列」語法。由於範圍內的order子句位於關聯上,所以我遇到了麻煩。

這是我已經試過,但沒有奏效:

scope :order_by_fiscal_year_and_grant_type, -> { 
    joins(money_pot: [:fiscal_year, :money_type]) 
    .order(fiscal_years: {end_date: :desc}, money_types: {short_name: :asc})} 

這裏是它返回的錯誤:

方向 「{:END_DATE =>:遞減}」 無效。有效方向爲:[:ASC,:DESC,:ASC,:DESC, 「ASC」, 「內容描述」, 「ASC」, 「DESC」]

我已經看過的ordering section和的hash conditions部活動記錄查詢接口Rails指南。

如何將此範圍完全轉換爲散列語法?

回答

3

have found不使用純字符串,唯一的辦法就是merge:再次

scope :order_by_fiscal_year_and_money_type, lambda { 
    joins(money_pot: [:fiscal_year, :money_type]) 
    .merge(FiscalYears.order(end_date: :desc) 
    .merge(MoneyType.order(:short_name) 
} 
+0

謝謝您的回答!你介意解釋爲什麼'lambda'被認爲比' - >'好? – Neil

+1

@Neil它只是一個「優先」的語法,[Rubocop](https://github.com/bbatsov/rubocop)的「人物」中的Ruby社區決定是常規的。在Rails中基本上使用''lambda''來代替多行範圍 –

+1

@Neil我肯定會推薦你安裝Rubocop並將它用在你的項目中 - 有時你甚至可以學到一些東西,更不用說改進你獲得的編碼風格了它;) –