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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With