sgk
sgk

Reputation: 169

Query based on the combination of two columns in Rails Active Record

I have a user model that has two columns i.e name and label. Combination of these columns is given in an array-like below

name_and_label_array = [["name1", "label1"], ["name2", "label2"], ["name3", label3"]

I want to query such that only those users should return whose name and label combination is present in the GIVEN array(name_and_label_array).

I tried with below code but it throws MYSQL syntax error

User.where("[name, label] in ?", name_and_label_array)

Please suggest some efficient ways to handle this in ActiveRecord.

In raw MYSQL, we can write in below way

select name, label from users where (name, label) in (('name1', 'label1'), ('name2', 'label2'));

Thank you in advance.

Upvotes: 0

Views: 659

Answers (1)

dezull
dezull

Reputation: 1010

You can generate the placeholders for the array of arrays.

placeholders = (['(?)'] * name_and_label_array.size).join(',')
User.where("(name, label) in (#{placeholders})", *name_and_label_array)

Upvotes: 2

Related Questions