我想知道是否可以将执行的查询结果转换为模型列表。
我正在使用Ruby和ActiveRecord,需要执行自定义SQL查询来连接两个或多个表。代码如下所示:
connection = ActiveRecord::Base.connection
sql = "select T1.f1, T2.f2 from T1 left join T2 on T1.id = T2.id"
@result = connection.execute(sql)
在Ruby代码中,我定义了一个模型来管理执行的SQL结果:
class Model
property :f1, :f2
end
有没有办法将@result转换为Model对象列表?所以我可以处理列表中的每个项目,如下所示
@result.each do |item|
puts item.f1
puts item.f2
end
答案 0 :(得分:7)
让您的模型继承ActiveRecord :: Base
class Model < ActiveRecord::Base
end
然后你就可以这样做了
connection = ActiveRecord::Base.connection
sql = "select T1.f1, T2.f2 from T1 left join T2 on T1.id = T2.id"
@result = Model.find_by_sql(sql)
puts @result.f1
答案 1 :(得分:0)
我现在所做的事情如下:
ActiveRecord::Base.connection_pool.with_connection do
connection = ActiveRecord::Base.connection
sql = "SELECT a.topic_seq, a.topic_id, a.topic_user_seq, a.topic_title, a.topic_header, t.tag_name AS topic_tag_name, to_char(a.topic_createtime::timestamp with time zone, 'Day, YYYY Mon DD'::text) AS topic_createtime FROM topics a LEFT JOIN tags t ON a.topic_tag = t.tag_seq;"
results = connection.execute(sql)
results.each do |row|
obj = Model.new(row['topic_seq', row['topic_id'], row['topic_user_seq']...],
puts obj.topic_seq
puts obj.topic_id
...
end
end
我只是想知道是否有另一种方法可以更轻松地将行转换为Model对象而不是使用Model构造函数?
答案 2 :(得分:0)
创建一个名为示例“ GenericObject”的通用模型:
class GenericObject < ActiveRecord::Base
end
执行sql并设置table_name:
sql = "select T1.f1, T2.f2 from T1 left join T2 on T1.id = T2.id"
go = GenericObject
go.table_name = "T1" #set this for do not show message "doesn't exist: SHOW FULL FIELDS FROM"
result = go.find_by_sql(sql)
获得结果:
p result
# [{"f1": 1, "f2": "x"}, {"f1": 2, "f2": "y"}]
p result.first.f1
# 1