我有一個AREL查詢,我生成了很多痛苦。供參考(對不起):如何從Rails中強制轉換數據類型connection.execute
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看起來像這樣正確的結果:
{ "id" => "13",
"name" => "Category 16",
"handle" => "category_16",
"total_skills" => "4",
"total_completed" => "0",
"total_verified" => "0"
}
因此,鑑於這種方法已經是一個怪物,我寧願不通過結果嘗試.inject
將所有數字轉換爲Fixnum。使用connection.execute
時,有沒有辦法將字段轉換爲適當的數據類型?
爲什麼查詢會返回字符串而不是整數id,total_skills,total_completed和total_verified? –
@JohnNaegle這就是問題,是啊:) –