简体   繁体   English

Rails 4在raw activerecord查询中获取列名

[英]Rails 4 get column names in raw activerecord query

I have some code that looks like the following: 我有一些代码如下所示:

query = <<-EOF
        select player_id, first_name, last_name,
            max(case when site_id = 1 then salary end) fd_salary,
            max(case when site_id = 2 then salary end) dd_salary,
            max(case when site_id = 3 then salary end) ss_salary,
            max(case when site_id = 4 then salary end) ds_salary,
            max(case when site_id = 7 then salary end) dk_salary,
            max(case when site_id = 8 then salary end) elite_salary
            from player_salaries ps
            where ps.gamedate = '2014-05-25'
            and sport_id = #{$MLB_SPORT_ID}
            group by player_id
    EOF

        salaries = PlayerSalary.connection.execute(query)

The problem is salaries in this case comes back as an array with values. 问题是这种情况下的salaries以带有值的数组形式返回。 These query is a bit complex and the names I'm using such as fd_salary , dd_salary and so forth aren't physical attributes in the PlayerSalary model. 这些查询有点复杂,我正在使用的名称如fd_salarydd_salary等不是PlayerSalary模型中的物理属性。 There's no way to do something like salaries.first.fd_salary . 没有办法像salaries.first.fd_salary那样做。 Is there a way to change the above in Rails 4 to get it access values by column name? 有没有办法在Rails 4中更改上面的内容以按列名访问它?

You could use find_by_sql for this: 您可以使用find_by_sql

find_by_sql(sql, binds = []) find_by_sql(sql,binds = [])

Executes a custom SQL query against your database and returns all the results. 对数据库执行自定义SQL查询并返回所有结果。 The results will be returned as an array with columns requested encapsulated as attributes of the model you call this method from. 结果将作为一个数组返回,并将请求的列封装为您调用此方法的模型的属性。 If you call Product.find_by_sql then the results will be returned in a Product object with the attributes you specified in the SQL query. 如果调用Product.find_by_sql则结果将在具有您在SQL查询中指定的属性的Product对象中返回。

So if you did: 所以,如果你这样做:

salaries = PlayerSalary.find_by_sql(query)

then you could say things like salaries.first.fd_salary . 然后你可以说像salaries.first.fd_salary这样的东西。 Just don't try to use columns that weren't in your query or try to change the returned PlayerSalary objects and expect anything useful to happen. 只是不要尝试使用查询中没有的列或尝试更改返回的PlayerSalary对象并期望发生任何有用的事情。

If you want to retrieve your records as a hash, with column names you can use mysql2 adapter directly with: 如果要将记录检索为哈希,使用列名称可以直接使用mysql2 adapter:

ActiveRecord::Base.connection.instance_variable_get('@connection').query("SELECT * FROM `users`", as: :hash).first

I was searching for another way to do it but had no luck. 我正在寻找另一种方法,但没有运气。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM