user2932090
user2932090

Reputation: 331

Rails + ActiveRecord: How do I write a condition "one or both are not true"?

In my model Listing, among other columns I have these two:

- seller_currency
- bidder_currency

The value of listings.seller_currency and listings.bidder_currency can be either 1 (USD) or 0 (EUR).

I am trying to get all listings, where seller_currency and bidder_currency is 0 (EUR) or at least one of them is 0 (EUR).

Is there a better way to write the condition than this?

Listing.where('(seller_currency=0) OR (bidder_currency=0) OR (seller_currency=0 AND bidder_currency=0)')

Upvotes: 0

Views: 58

Answers (2)

stevo999999
stevo999999

Reputation: 608

You only need one or condition and it covers the case where they are both 0. This way is preferable because it is a quicker query since it evaluates both columns at the same time. Also, in case you wanted to use variables, the question mark stops sql injection.

Listing.where("(seller_currency=?) OR (bidder_currency=?)",0,0)

Upvotes: 0

mechnicov
mechnicov

Reputation: 15248

According to your example, it is enough to fulfill at least one condition.

Listing.where(seller_currency: 0).or(Listing.where(bidder_currency: 0))

Upvotes: 3

Related Questions