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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top