【问题标题】:How to pluck "as alias_name" from rails active record query如何从 Rails 活动记录查询中提取“as alias_name”
【发布时间】:2016-10-03 13:13:35
【问题描述】:

我有这个问题:

Client.select("name as dname")

哪个工作正常。

Client.select("name as dname").first.dname
=> "Google"

现在我想将所有 dnames 作为一个数组获取,但 pluck 方法不起作用,因为 dname 不是列名。

2.2.5 :040 > Client.select("name as dname").pluck(:dname)
   (0.6ms)  SELECT dname FROM "clients"
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "dname" does not exist

如何获取 dnames 数组? 有没有类似 pluck 的方法适用于使用 as 定义的列名别名。

我能做到

Client.select("name as dname").map{|d| d.dname}

但是循环遍历每条记录对我来说没有任何意义

【问题讨论】:

  • 试试这个Client.select("name as dname").map{|d| d.dname}
  • @SantoshSharma 我知道这是可能的,但循环不是最好的解决方案,因为我们已经从数据库中获取了 dname 列表,为什么我们需要再次循环遍历每个结果。?

标签: sql ruby-on-rails postgresql ruby-on-rails-4 activerecord


【解决方案1】:

好吧,我对 pluck 的理解是错误的。从 apidock 我明白了

使用 pluck 作为快捷方式来选择一个或多个属性,而无需加载一堆记录来获取您想要的属性。

所以,

Client.select("name as dname").pluck(:dname)

应该这样写

Client.pluck("name as dname")

【讨论】:

    【解决方案2】:

    使用此代码:

    Client.select("name as dname").map{|d| d.dname}
    

    【讨论】:

      【解决方案3】:

      selectpluck 不能很好地配合使用,但我使用了一种解决方法,将别名列连接到查询对象上,从而允许采摘。我通常把这样的连接写成以with_开头的作用域

      class Client
        scope :with_dname , -> {
          # Build a subquery SQL snippet
          # Since we will be joining it onto the base table, we need to select the id column as well
          subquery = select("name AS dname, #{table_name}.id").to_sql
      
          # join the subquery to base model
          joins("JOIN (#{subquery}) as addendum ON addendum.id = #{table_name}.id")
        }
      end
      
      # this will work 
      Client.with_dname.first.pluck(:dname) #=> ["Google"]
      
      # this may be more efficient
      Client.limit(1).with_dname.first.pluck(:dname) #=> ["Google"]
      

      【讨论】:

      • 我正在类似的模型上尝试这种方法,但没有任何运气。 @Epigene 也许您可以提供一些见解。 scope :with_dud, -> { subquery = select("(renewal_date - current_date) AS days_until_due, #{table_name}.id").to_sql joins("JOIN (#{subquery}) as rd on rd.id = #{table_name }.id") } 在控制台 ---> Model.with_dud.first.attributes 我看不到 days_until_due 属性列出...抱歉,我无法使此评论的格式更易于阅读:(
      • @JoelGrannas 不确定这些合并字段是否显示在属性中,请尝试 Model.with_dud.first.days_until_due 验证该值是否存在。也许退后一步,重现原始示例中的行为,然后进行试验。
      • @Epigene - 谢谢,这个解决方案帮助我解决了类似的问题。
      猜你喜欢
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      相关资源
      最近更新 更多