将PG :: Result转换为Active Record模型

时间:2015-06-14 04:44:40

标签: ruby-on-rails ruby rails-activerecord

pg-ruby允许您一次向数据库发送多个查询,这有助于最大限度地减少对数据库的访问次数:

results = []
conn.send_query('QUERY1;QUERY2;QUERY3')
conn.block
while result = conn.get_result
  results << result
end

鉴于任何result我已经知道Active Record模型,将结果转换为模型的适当方法是什么?现在我正在做以下事情:

fields = result.fields
models = result.values.map { |value_set| 
  Model.new(Hash[fields.zip(value_set)])
}

该方法的问题在于,每个Active Record对象似乎都不是#persisted?,因为它们已使用.new进行实例化。

2 个答案:

答案 0 :(得分:10)

我认为你想要的是ActiveRecord::Base.instantiate方法。它将正确处理new_record? / persisted?问题,并为单表继承找到正确的类。

例如:

fields = result.fields
models = result.values.map { |value_set| 
  Model.instantiate(Hash[fields.zip(value_set)])
}

答案 1 :(得分:0)

它看起来像黑客但无论如何

fields = result.fields
models = result.values.map { |value_set| 
  hash = Hash[fields.zip(value_set)]
  model = Model.new(hash)
  # some attributes may not be assigned i.e. id, created_at and updated_at
  # in that case you can assign them manually:
  # model.id = hash["id"] 
  model.instance_variable_set :@new_record, false
  model
}