Skip to content

Instantly share code, notes, and snippets.

@kbrock
Last active March 15, 2016 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbrock/60015a72590cf7f296d2 to your computer and use it in GitHub Desktop.
Save kbrock/60015a72590cf7f296d2 to your computer and use it in GitHub Desktop.
Trying to mix and match active record AND OR
create table tst(val int);
insert into tst values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
select val from tst where (val=2) and (mod(val,2)=0) or (val >= 6);

| val |

| 2| | 6| | 7| | 8| | 9| | 10|

select val from tst where (val=2 and mod(val,2)=0) or (val >= 6);

| val |

| 2| | 6| | 7| | 8| | 9| | 10| (6 rows)

select val from tst where (val=2) and (mod(val,2)=0 or val >= 6);

| val |

| 2 | (1 row)

GOAL:

SELECT "vms".* FROM "vms"
WHERE "vms"."ems_id" = 2
  AND ("vms"."name" = '3' OR "vms"."type" = 'abc')
  AND "vms"."id" = 3

#A

VmOrTemplate.where(:ems_id => 2)
            .where(:name => 3).or(VmOrTemplate.where(:type => 'abc'))
            .where(:id => 3).to_sql
SELECT "vms".* FROM "vms"
WHERE ("vms"."ems_id" = 2 AND "vms"."name" = '3' OR "vms"."type" = 'abc')
  AND "vms"."id" = 3

aka

SELECT "vms".* FROM "vms"
WHERE ("vms"."ems_id" = 2 AND "vms"."name" = '3') OR ("vms"."type" = 'abc')
  AND "vms"."id" = 3

#B

VmOrTemplate.where(:ems_id => 2)
            .where(VmOrTemplate.where(:name => 3).or(VmOrTemplate.where(:type => 'abc')))
            .where(:id => 3).to_sql
SELECT "vms".* FROM "vms"
WHERE "vms"."ems_id" = 2
  AND "vms"."id" = 3

C

rel = VmOrTemplate.where(:ems_id => 2) ; nil
rel = rel.where(:name => 3).or(rel.where(:type => 'abc')) ; nil
rel = rel.where(:id => 3) ; rel.to_sql
SELECT "vms".*
FROM "vms"
WHERE ("vms"."ems_id" = 2 AND "vms"."name" = '3' OR "vms"."ems_id" = 2 AND "vms"."type" = 'abc')
AND "vms"."id" = 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment