AnApprentice
AnApprentice

Reputation: 110940

How to combine two conditions in a where clause?

I have the following:

time_range = (1.month.ago.beginning_of_month..1.month.ago.end_of_month)

Comment.where(:created_at => time_range).count

How can I add to the where clause with a statement like:

.where("user_id is not in (?)",[user_ids]).

How can I combine the two? Thanks

Upvotes: 43

Views: 69547

Answers (3)

Siwei
Siwei

Reputation: 21549

solution 1: ( I prefer , more easy to understand)

Just write it like raw SQL:

Comment.where(
   "(user_id > ? AND user_id < ? ) OR (created_at > ? AND created_at < ?)",
   100, 200, "2022-06-01", "2022-06-05")

solution 2:

Comment.
  where(:created_at => time_range).
  where("user_id is not in (?)",[user_ids])

which will produce SQL like : select ... where ... AND ...

Upvotes: 88

shiva kumar
shiva kumar

Reputation: 11414

User.where(name: 'Joe', email: '[email protected]')

Upvotes: 23

Sujith Sudersan
Sujith Sudersan

Reputation: 231

User.where(["name = ? and email = ?", "Joe", "[email protected]"])

This will be fine.

Upvotes: 23

Related Questions