On the Rails 3, ActiveRecord generate QSL through DSL "Arel".
There are many simple query sample codes are available, but complex one is a little.
This post shows how to generate complex "OR" query.
I want to write such a code below (like Propel for PHP):
def foo
# generate condition A
# generate condition B
some_array.each do |h|
# generate condition A to N
end
# return condition which is concatenated by "OR" clause.
end
One simple idea, I wrote (like Doctrine for PHP):
Foo.where(CONDITION1).or(CONDITION2).or(CONDITION3)
But it does not work.
A correct answer is below (use "scoped"):
conds = Array.new
f = Foo.scoped
conds << f.tables[:field_name].eq('FOO')
some_array.each do |c|
conds << f.tables[:field_name].SOME_METHOD()
end
cond = nil
conds.each do |c|
if not cond
cond = c
else
cond = cond.or(c)
end
end
return Foo.where(cond)
The code generates "(((COND1 OR COND2) OR COND3) OR COND4)" where clause.
0 件のコメント:
コメントを投稿