Forum: Ruby on Rails Active record :find having an if statement inside the conditions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0bdaf2a5cf0a401d2ee4377b9ce47581?d=identicon&s=25 Tyl Tan (tyanlion)
on 2008-12-09 21:01
(Received via mailing list)
Hi, i was just wondering if its is possible to put a if statment
inside the find conditions


for example:

grovery_price = model.find(:first, :conditions => [ "if x = ? then y
must = ?", 200, 300]

I have been googling for some time for a solution to this but i just
can't seem to find any.
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2008-12-09 21:12
Tyl Tan wrote:
> Hi, i was just wondering if its is possible to put a if statment
> inside the find conditions
>
>
> for example:
>
> grovery_price = model.find(:first, :conditions => [ "if x = ? then y
> must = ?", 200, 300]
>
> I have been googling for some time for a solution to this but i just
> can't seem to find any.

Does

:conditions => ["(x = ? and y = ?) or x <> ?", 200, 300, 200]

work?
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2008-12-09 21:14
Or is it just:

:conditions => ["(x = ? and y = ?)", 200, 300]

i.e., do you want the items where x != 200 or not?
0bdaf2a5cf0a401d2ee4377b9ce47581?d=identicon&s=25 Tyl Tan (tyanlion)
on 2008-12-09 21:19
(Received via mailing list)
If x equal 200 then I want the find to check that y is equal to 300 but
if x is not equal to 200 there should be no check with y
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2008-12-09 21:32
Tyl Tan wrote:
> If x equal 200 then I want the find to check that y is equal to 300 but
> if x is not equal to 200 there should be no check with y

Well,

:conditions => ["x <> ? or (x = ? and y = ?)", 200, 200, 300]

If SQL short-circuits the logic, that shouldn't check y when x != 200
0bdaf2a5cf0a401d2ee4377b9ce47581?d=identicon&s=25 Tyl Tan (tyanlion)
on 2008-12-09 21:39
(Received via mailing list)
Thanks I'll try it out when I have the time
This topic is locked and can not be replied to.