Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert executed SQL result to a list of Model object

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
like image 952
huynq9 Avatar asked Jun 07 '14 12:06

huynq9


1 Answers

Have your model inherit ActiveRecord::Base

class Model < ActiveRecord::Base
end

Then you can just do it like this

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
like image 144
Eyeslandic Avatar answered Oct 03 '22 02:10

Eyeslandic