ActiveRecord::Base.connection.execute(sql)
结果不是类型化的,因此它们都是字符串作为示例
ActiveRecord::Base.connection.execute(sql).entries
=> [{"id" => "1", "length" => "120", "content" => "something"},{"id" => "2", "length" => "200", "content" => "blahblah"}]
是否可以在activerecord中执行原始事务并返回类型转换结果?
答案 0 :(得分:1)
考虑将您的SQL语句显示为视图,并创建新视图以与视图进行交互。
这是一个我用视图支持AR的项目: https://github.com/michaelkirk/household-account-mgmt/blob/develop/app/models/monthly_report.rb
class CreateMonthlyReports < ActiveRecord::Migration
def up
sql = <<-SQL
create view monthly_reports as
select date_part('year', created_at) as year, date_part('month', created_at) as month, sum(purchase_amount) as purchases_amount, sum(investment_amount) as investments_amount
from (
select * from transactions
left join
(select id as purchase_id, amount as purchase_amount from transactions where credit = false)
as purchases on transactions.id = purchases.purchase_id
left join
(select id as investment_id, amount as investment_amount from transactions where credit = true)
as investments on transactions.id = investments.investment_id)
as classified_transactions
group by year, month
order by year, month
SQL
execute(sql)
end
def down
sql = <<-SQL
drop view monthly_reports
SQL
execute(sql)
end
然后,因为你已经将你的复杂性抽象到数据库视图中,对于所有AR的意图/目的,它就像一个表,你的模型和控制器看起来完全是香草。
class MonthlyReport < ActiveRecord::Base
MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
def time_period
"#{month} #{year}"
end
def month
MONTHS[self[:month] - 1]
end
def year
self[:year].to_i
end
end
然后你可以做像
这样的事情class MonthlyReportsController < ApplicationController
def index
@monthly_reports = MonthlyReport.all
end
end
请注意,因为这是一个DB视图,所以您将无法进行插入操作。我不确定如果你尝试会发生什么。
答案 1 :(得分:0)
我认为你指的是ORM(对象关系映射)
首先,connection.execute
将返回一个Mysql适配器,您可以在其中迭代行
您无法将字符串数组(您拥有的结果)转换为ActiveRecord对象(我猜这就是您所谓的类型转换)
您可以使用find_by_sql
。
<强>实施例强>
Blog.find_by_sql("select * from blog")
# => [#<Blog id: 1, name: "first blog", description: nil, record_status_id: 1>]
使用此方法,您可以从原始SQL获取ActiveRecord对象
答案 2 :(得分:0)
实际上,可以将结果转换为ActiveRecord对象(请参阅find_by_sql
方法here)或本地Ruby类型(请参阅this StackOverflow answer)。