Ossie Ossie - 2 years ago 105
Ruby Question

How to merge the results of two ActiveRecord queries?

I have the following code in my controller

@production_versions =
Version.where(:item_type => Production)
.where("object like ?", "%miniature_id: #{@miniature.id}%") |
Version.where(:item_type => Production)
.where("object_changes like ?", "%miniature_id: #{@miniature.id}%")

That returns all of the first query results followed by all of the second query results. How can I merge the two so that they appear as one list?

Answer Source

ActiveRecord doesn't provide a way to combine queries with "or", but you can do it in SQL:

@production_versions =
  Version.where(:item_type => Production)
    .where("object like ? or object_changes like ?", 
      "%miniature_id: #{@miniature.id}%", "%miniature_id: #{@miniature.id}%")

As well as interleaving the results, doing it this way is more efficient, since it will only run one database query and will only instantiate each object once even if it satisfies both conditions. If you want to be sure of order, however, you should order by something.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download