pg-ruby
allows you to send multiple queries to the database in one shot, which helps minimize the number of trips made to the database:
results = []
conn.send_query('QUERY1;QUERY2;QUERY3')
conn.block
while result = conn.get_result
results << result
end
Given that for any result
I already know the Active Record model, what's the appropriate way to convert the result into models? Right now I'm doing the following:
fields = result.fields
models = result.values.map { |value_set|
Model.new(Hash[fields.zip(value_set)])
}
The problem with that method is that each of the Active Record objects don't appear to be #persisted?
since they've been instantiated with .new
.
I think what you want is the ActiveRecord::Base.instantiate
method. It will correctly handle the new_record?
/persisted?
issue, as well as finding the correct class for single-table inheritance.
For example:
fields = result.fields
models = result.values.map { |value_set|
Model.instantiate(Hash[fields.zip(value_set)])
}
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