我使用find_by_sql来获取两个表的UNION,这些表有一些比Model更多的列,这些列曾经调用过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模型的正方形如下:
@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