实例化exec_query的STI继承模型结果

时间:2019-01-29 21:30:10

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

给出以下返回哈希值的查询:

def query
  sql = %(SELECT * FROM components
          INNER JOIN brands_components ON brands_components.component_id = components.id
          INNER JOIN brands ON brands.id = brands_components.brand_id
          INNER JOIN components_templates ON components.id = components_templates.component_id
          WHERE components_templates.template_id = #{@template.id}
          AND (components.user_id IS null OR components.user_id = #{@user.id})
          AND brands.id = #{@user.brand_id})
  ActiveRecord::Base.connection.exec_query(sql)
end

如何将结果实例化为ActiveRecord集合(尤其是如果它们表示不同的模型,例如,从Component继承的STI)?

1 个答案:

答案 0 :(得分:2)

将sql传递给find_by_sql将实例化模型,因此将方法更改为

for (example <- List(
  List(1, 2, 2, 2, 3, 4, 7, 8),
  List(1, 2, 3, 4, 7, 7, 7, 8),
  List(1, 2, 3, 4, 7, 1, 2, 3, 5, 7, 8)
)) {
  println(findDelimitedSlices(example, 2, 7))
}

应该给您您想要的。还将为每个记录实例化正确的子类。