繁体   English   中英

ActiveRecord执行原始事务类型转换?

[英]ActiveRecord execute raw transaction typecasting?

ActiveRecord::Base.connection.execute(sql)

结果不是类型化的所以它们都是字符串作为示例ActiveRecord::Base.connection.execute(sql).entries

=> [{"id" => "1", "length" => "120", "content" => "something"},{"id" => "2", "length" => "200", "content" => "blahblah"}]

是否可以在activerecord中执行原始事务并返回类型转换结果?

考虑将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视图,所以您将无法进行插入。 我不确定如果你尝试会发生什么。

我认为你指的是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对象

实际上,您可以将结果转换为ActiveRecord对象(请参阅此处find_by_sql方法)或作为本机Ruby类型(请参阅此StackOverflow答案 )。

暂无
暂无

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

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