sunil
sunil

Reputation: 1040

rails where for checking multiple condition

Is there any short way to right following query in rails:

Message.where("(user_id = 8 AND  commentable_id= 84) OR (user_id=84 AND commentable_id=8) ")

Thanks

Upvotes: 1

Views: 72

Answers (2)

varunvlalan
varunvlalan

Reputation: 950

I think this should work:

arr = [8, 84] Message.where(user_id: arr, commentable_id: arr)

Above query will have 4 combinations:

      user_id      commentable_id

  1. 8              8
  2. 8              84
  3. 84            8
  4. 84            84

Out of above combinations, 1st and 4th are invalid. Thus it should get you results.

Upvotes: 3

Christian Rolle
Christian Rolle

Reputation: 1684

Maybe Arel is what you are looking for in terms of readability, like:

class Message < ActiveRecord::Base
  def self.user_id_and_comment_id user_id, comment_id
    where user_and_comment(user_id, comment_id).or(user_and_comment comment_id, user_id)
  end
  private
  def self.user_and_comment user_id, comment_id
    table[:user_id].eq(user_id).and(table[:commentable_id].eq comment_id)
  end

  def self.table
    self.arel_table
  end
end

Message.user_id_and_comment_id 8, 84

Extracting the stuff into separate models and a scopes helps composing queries a lot and makes them reuseable for other related queries. Btw. I assume you did not hard coded the ids into the SQL.

Upvotes: 3

Related Questions