2016-09-27 71 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并将它用在你的项目中 - 有时你甚至可以学到一些东西,更不用说改进你获得的编码风格了它;) –