1

我已经使用 find_by_sql 来获取两个表的 UNION,这两个表的列比用于调用 find_by_sql 的模型多一些,

例如:

class Shape < ActiveRecord::Base
   # columns
   # shape_id -> Integer
end

class Circle < ActiveRecord::Base
   # columns
   # circle_id -> Integer
   # created_at -> Datetime 
   # update_at -> Datetime 
end

class Square < ActiveRecord::Base
   # columns
   # square_id -> Integer
   # created_at -> Datetime 
   # update_at -> Datetime 
end

我使用 Shape 模型对圆形和正方形进行了 UNION,如下所示:

@shapes = Shape.find_by_sql("select circle_id as id, created_at, updated_at from circles UNION select square_id as id, created_at, updated_at from squares")

现在,当我使用 @shapes 显示所有带有 created_at 和 updated_at 的记录时,它总是在字符串对象中返回,如下所示:

for shape in @shapes
  puts shape['id'].class.inspect # String
  puts shape['created_at'].class.inspect # String
  puts shape['updated_at'].class.inspect # String
end

现在,什么是最好的方法,我可以将所有值作为数据库中定义的类型对象,如下所示:

for shape in @shapes
  puts shape['id'].class.inspect # Integer
  puts shape['created_at'].class.inspect # DateTime
  puts shape['updated_at'].class.inspect # DateTime
end
4

0 回答 0