【问题标题】:Scope Change from Pure String Syntax to Hash Syntax范围从纯字符串语法更改为哈希语法
【发布时间】:2016-09-28 04:33:40
【问题描述】:

我在模型中有以下范围:

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=>:desc}”无效。有效方向为:[:asc, :desc, :ASC, :DESC, "asc", "desc", "ASC", "DESC"]

我查看了 Active Record Query Interface Rails Guides 的 ordering sectionhash conditions 部分。

如何将此范围完全转换为哈希语法?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    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)
    }
    

    【讨论】:

    • 再次感谢您的回答!你介意解释一下为什么lambda 被认为比-&gt; 更好吗?
    • @Neil 这只是一种“首选”语法,Rubocop 的“人”中的 Ruby 社区决定采用传统语法。基本上使用lambda 而不是-&gt; 用于Rails 中的多行范围
    • @Neil 我绝对会推荐你安装 Rubocop 并在你的项目中使用它——你有时甚至可以学到一些东西,更不用说你获得的编码风格的改进 ;)
    猜你喜欢
    • 2017-02-05
    • 2015-05-27
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2014-10-29
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多