开发者

Rails - Building Conditions for Use in a Query

开发者 https://www.devze.com 2023-04-05 03:06 出处:网络
I usually like to build a conditions hash like this below: conditions = {} conditions[:color] = \"black\"

I usually like to build a conditions hash like this below:

conditions = {}
conditions[:color] = "black"
conditions[:doors] = 4
conditio开发者_StackOverflowns[:type] = "sedan"

Cars.find(:all, :conditions=>conditions)

But how would I add a date range into this for something like:

year >= '2011-01-01' and year < '2011-02-01'


I am assuming you are using Rails 2.3.x and year is a date column.

conditions = {}
conditions[:color] = "black"
conditions[:doors] = 4
conditions[:type] = "sedan"
# create a date range
conditions[:year] = (Date.parse("2011-01-01")...Date.parse("2011-02-01"))

Car.all(:conditions => conditions)

If you want to do even more complex queries in 2.3.x use the AR Extensions gem. Read this article for more details.


If you're on Rails 3, why not use AREL?

Cars.where(:color => "black").
     where(:doors => 4).
     where(:type => "sedan").
     where("year >= '2011-01-01'").
     where("year < '2011-02-01'")

Btw, don't use :type as a field name. Rails uses this for STI.

On Rails 2.3, I'd just build up conditions as a String instead.


You can build a up query through relations. The query will not be executed until it needs to be evaluated. This is nice for searches where some parameters are optional.

@cars = Cars.where(:color => "black")
@cars = @cars.where(:doors => 4)
@cars = @cars.where("year >= '2011-01-01'")
@cars = @cars.where("year <= '2011-02-01'")

Or you could just merge all that together into one:

Cars.where(["color=? AND doors=? AND year >= ? AND year <= ?", "black", 4, "2011-01-01", "2011-02-01"]

UPDATE: For Rails < 3

@cars = Cars.scoped(:conditions => {:color => "black"})
@cars = @cars.scoped(:conditions => {:doors => 4})
@cars = @cars.scoped(:conditions => "year >= '2011-01-01'")
@cars = @cars.scoped(:conditions => "year <= '2011-02-01'")

OR

Cars.all(:conditions => ["color=? AND doors=? AND year >= ? AND year <= ?", "black", 4, "2011-01-01", "2011-02-01"]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号