1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Allow HAVING to take multiple conditions, like WHERE

This commit is contained in:
Jon Leighton 2011-01-04 07:11:34 +08:00 committed by Aaron Patterson
parent 597fe15809
commit 8bc0fce00b
2 changed files with 28 additions and 9 deletions

View file

@ -97,10 +97,8 @@ module Arel
self self
end end
def having expr def having *exprs
expr = Nodes::SqlLiteral.new(expr) if String === expr @ctx.having = Nodes::Having.new(collapse(exprs, @ctx.having))
@ctx.having = Nodes::Having.new(expr)
self self
end end
@ -211,16 +209,22 @@ switch to `compile_insert`
end end
private private
def collapse exprs def collapse exprs, existing = nil
return exprs.first if exprs.length == 1 exprs = exprs.unshift(existing.expr) if existing
exprs = exprs.compact.map { |expr|
create_and exprs.compact.map { |expr|
if String === expr if String === expr
# FIXME: Don't do this automatically
Arel.sql(expr) Arel.sql(expr)
else else
expr expr
end end
} }
if exprs.length == 1
exprs.first
else
create_and exprs
end
end end
end end
end end

View file

@ -99,13 +99,28 @@ module Arel
end end
end end
describe '#having' do describe 'having' do
it 'converts strings to SQLLiterals' do it 'converts strings to SQLLiterals' do
table = Table.new :users table = Table.new :users
mgr = table.from table mgr = table.from table
mgr.having 'foo' mgr.having 'foo'
mgr.to_sql.must_be_like %{ SELECT FROM "users" HAVING foo } mgr.to_sql.must_be_like %{ SELECT FROM "users" HAVING foo }
end end
it 'can have multiple items specified separately' do
table = Table.new :users
mgr = table.from table
mgr.having 'foo'
mgr.having 'bar'
mgr.to_sql.must_be_like %{ SELECT FROM "users" HAVING foo AND bar }
end
it 'can have multiple items specified together' do
table = Table.new :users
mgr = table.from table
mgr.having 'foo', 'bar'
mgr.to_sql.must_be_like %{ SELECT FROM "users" HAVING foo AND bar }
end
end end
end end