marcamillion
marcamillion

Reputation: 33755

How do I do a where query on a SQL column against multiple values?

This is what my query looks like:

Connection.where("invited_user_id = :user_a_id AND inviter_user_id = :user_b_id", user_a_id: self.inviter.try(:id), user_b_id: self.invited.try(:id)).exists?

What I would like to do is basically check invited_user_id against multiple options, e.g. something like invited_user_id = [:user1, :user2]. But that doesn't work.

How can I check to see if the value in the column invited_user_id is in either of the variables :user1, :user2 or any other of multiple variables.

Is that possible without using an explicit OR approach that's less DRY?

Upvotes: 0

Views: 1187

Answers (2)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

Never put values directly in a query, that's not safe. Parameterize your query using the ? operator.

invited_user_ids = [:user1, :user2]
Connection.where("invited_user_id IN (?)", invited_user_ids)

Upvotes: 2

infused
infused

Reputation: 24337

The Hash form of where accepts array of values, so:

Connection.where(invited_user_id: [1, 2, 3, 4, 5])

That will find all records where invited_user_id is any of the values listed in the array.

Upvotes: 2

Related Questions