Convert executed SQL result to a list of Model object
Posted
by
huynq9
on Stack Overflow
See other posts from Stack Overflow
or by huynq9
Published on 2014-06-07T12:59:08Z
Indexed on
2014/06/07
15:24 UTC
Read the original article
Hit count: 247
I'm wondering that is it possible to convert the executed query result to a list of models.
I'm using Ruby with ActiveRecord and need to execute custom SQL query to join two or many tables. The code looks like below:
connection = ActiveRecord::Base.connection
sql = "select T1.f1, T2.f2 from T1 left join T2 on T1.id = T2.id"
@result = connection.execute(sql)
In Ruby code, I defined a models to manage the executed SQL result:
class Model
property :f1, :f2
end
Is there any way to convert @result to list of Model object? so I can deal with each item in the list as following
@result.each do |item|
puts item.f1
puts item.f2
end
© Stack Overflow or respective owner