8bithero
8bithero

Reputation: 1619

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?

Upvotes: 0

Views: 211

Answers (1)

Akshay Goyal
Akshay Goyal

Reputation: 925

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

Upvotes: 1

Related Questions