gpt4 book ai didi

sql - rails : setting column alias attribute with find_by_sql

转载 作者:行者123 更新时间:2023-12-04 00:48:53 24 4
gpt4 key购买 nike

当我在带有 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,即使一个值肯定是从查询中返回的。

谁能向我解释为什么没有在对象中设置属性?

最佳答案

您不需要使用 attr_accessor ,见neutrino的解释。您只需要使用 attributes 访问您的虚拟列。哈希。这个问题同Rails: find_by_sql and virtual column .您的示例的示例代码:

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

关于sql - rails : setting column alias attribute with find_by_sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2272846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com