SkRoR
SkRoR

Reputation: 1199

How to write Active Record with "and" and "or" conditions in Ruby

I want to write Active Record with three and condition(must) and two or conditions.

I wrote this:

@properties = Property.where(category_id: 2).
                       where(status: 3).
                       where(p_type: 'sell')`

This lists the query with and conditions.

I need to include two or conditions at the end.

It tried this but got an error:

@properties = Property.where(category_id: 2).
                       where(status: 3).
                       where(p_type: 'sell').
                       or(location: @location).
                       or(featured: '1)`

How do I do it?

Upvotes: 0

Views: 898

Answers (2)

Amit Sharma
Amit Sharma

Reputation: 3477

You can try this.

@properties = Property.where(category_id: 2, status: 3).where("(p_type = ? OR location = ? OR featured = ?)", 'sell', @location, '1')

Upvotes: 0

Muhammad Ali
Muhammad Ali

Reputation: 2183

@properties=Property.where("(category_id = ? AND status = ? ) OR (location = ? OR featured = ?)", "2", "3", @location, "1")

Upvotes: 2

Related Questions