Search code examples
sqlruby-on-railsactiverecordruby-on-rails-5arel

Find all records that contain a combination of attributes from an array


I have a table called LayerProducts that contains layer_id and product_id attributes.

I would like to create a query where I can pass in an array of arrays that looks like this:

[ [:layer1_id, :product1_id], [:layer2_id, :product2_id], [:layer3_id, :product3_id] ]

and return all records of LayerProduct that contain any of the combinations supplied.

The parent array is not fixed-length, so the query would need to be dynamic to accommodate any number of combinations.

Is this possible and if so, how would I go about creating this query using either SQL or active record?


Solution

  • You can construct a raw sql and use active record. Something like this:

    def self.for_multiple_lp(arr=[])
      # Handle case when arr is not in the expected format.
      condition = arr.collect{|a| "(layer_id = #{a[0]} AND product_id = #{a[1]})"}.join(" OR ")
      where(condition)
    end
    

    For just raw sql without activerecord you can refer this