mysqlruby-on-railsactiverecordactive-relation

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


Solution

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