简体   繁体   中英

Hash conditions in Active Record

As I know I can rewrite this active record query

Some.where("a = :a and b = :b", { :a => params[:a], :b => params[:b] })

this way:

Some.where(:a => params[:a], :b => params[:b])

Now I need to rewrite this query:

Some.where("a = :a and b > :b", { :a => params[:a], :b => params[:b] })

How can I get it ?

I can use range conditions:

Some.where(:a => params[:a], :b => params[:b]+1..100000)

But I can not be sure in the constant 100000.

I can't see why you "need" to rewrite it. It works as-is, and there is no way to do it properly with hash-based conditions.

That said, if you aren't a fan of SQL making a mess in your Ruby, you could take a look at the excellent Squeel gem which lets you rewrite things like

where("name LIKE :name AND salary < :salary", {:name => "A%", :salary => 50000})

as

where{(name =~ "A%") & (salary < 50000)}

which I think is pretty cool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM