如何从投Rails的connection.execute数据类型 [英] How to cast datatype from Rails connection.execute
问题描述
我有,我有太多的痛苦产生AREL查询。供参考(不好意思):
I've got an AREL query that I generated with much pain. For reference (sorry):
def self.summarize_user(user)
c = Arel::Table.new(:categories)
s = Arel::Table.new(:skills)
cp = Arel::Table.new(:completions)
query = c.project(c[:id], c[:name], c[:handle])
.project(s[:id].count.as("total_skills"))
.project(cp[:id].count.as("total_completed"))
.project(cp[:verified_on].count.as("total_verified"))
.join(s).on(s[:category_id].eq c[:id])
.join(cp, Arel::Nodes::OuterJoin).on(cp[:skill_id].eq s[:id])
.where(cp[:user_id].eq(user.id).or(cp[:user_id].eq nil))
.group(c[:id], c[:name], c[:handle])
# this is the relevant bit
connection.execute(query.to_sql)
end
这执行,并让我从DB正确的结果是这样的:
This executes and gives me proper results from the DB that look like this:
{ "id" => "13",
"name" => "Category 16",
"handle" => "category_16",
"total_skills" => "4",
"total_completed" => "0",
"total_verified" => "0"
}
因此,鉴于这种方法已经是一个怪物,我宁愿不通过的结果尝试 .inject
投所有的数字到Fixnum对象。有没有一种方法,在使用 connection.execute
,投领域到正确的数据类型?
So, given that method is already a monster, I'd rather not try to .inject
through the results to cast all the numbers into Fixnum. Is there a way, when using connection.execute
, to cast fields to their proper datatypes?
推荐答案
您可以利用的的find_by_sql 和 to_json
json_records = Arel::Table.find_by_sql(query.to_sql).to_json
然后你就可以提取您的结果像
Then you can extract your results like
result = JSON.parse json_records
有几种方法可以转换的ActiveRecord
对象散
。这只是我个人的preference。
There are several ways to convert ActiveRecord
objects to hash
. This is just my personal preference.
这篇关于如何从投Rails的connection.execute数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!