Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PG::Result to an Active Record model

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.

like image 891
fny Avatar asked Jun 14 '15 04:06

fny


1 Answers

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)])
}
like image 128
theunraveler Avatar answered Sep 20 '22 19:09

theunraveler