【问题标题】:Rails: setting column alias attribute with find_by_sqlRails:使用 find_by_sql 设置列别名属性
【发布时间】:2010-02-16 12:34:54
【问题描述】:

当我在使用 find_by_sql 的查询中使用列别名时,它似乎没有在结果对象中设置,即使我为属性添加了 attr_accessor。

class Country < ActiveRecord::Base

  attr_accessor :average_score

  def self.sorted_by_average_score
    sql = "SELECT country_id, AVG(score) AS average_score, countries.name " +
    "FROM players " +
    "INNER JOIN countries ON players.country_id = countries.id " +
    "GROUP BY country_id "
    Country.find_by_sql(sql)
  end
end

我希望能够做到这一点:

countries = Country.sorted_by_average_score.first.average_score

...但它总是返回 nil,即使从查询中肯定返回了一个值。

谁能解释一下为什么对象中没有设置属性?

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    您不需要使用attr_accessor,请参阅中微子的解释。您只需要使用attributes 哈希来访问您的虚拟列。这个问题和Rails: find_by_sql and virtual column一样。您的示例的示例代码:

    countries = Country.sorted_by_average_score.first.attributes['average_score']
    

    【讨论】:

      【解决方案2】:

      因为attr_accessors 与 ActiveRecord 处理您的列的方式无关。我已经在this question 中展示了它。基本上所有涉及列的查找器中发生的事情都与attributes 哈希一起使用,而不是与访问器声明的实例变量一起使用。

      编辑:实际上我的回答并没有完全回答这个问题。它只是解释了为什么attr_accessor 在这里没有任何帮助。期待看到有人完成剩下的工作:)

      【讨论】:

      • 虽然你的答案没有回答实际问题是正确的,但很高兴知道引擎盖下发生了什么。谢谢。
      猜你喜欢
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多