Search code examples
ruby-on-railsruby-on-rails-3activerecord

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


Solution

  • 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 ...