Hi
I have a form on View and I have to construct condition for query
depending fields which user filled in form.
I should write something like:
cond
if params[par1]
cond = " par1 = #{par1} "
if params[par2]
cond += " AND par2 = #{par2} "
etc…
Client.all(:conditions => cond)
…
…
May be someone know more rational way how to do it in RoR?
Thanks in advance!
Stanislav O. wrote:
Hi
I have a form on View and I have to construct condition for query
depending fields which user filled in form.
I should write something like:
cond
if params[par1]
cond = " par1 = #{par1} "
if params[par2]
cond += " AND par2 = #{par2} "
NO! NEVER EVER DO THAT! You’re leaving yourself wide open to SQL
injection.
etc…
Client.all(:conditions => cond)
…
…
May be someone know more rational way how to do it in RoR?
Thanks in advance!
Well, conditions can take a hash, so how about
conditions = {}
[:p1, :p2, :p3].each do |p|
if params[p]
conditions[p] = params[p]
end
end
Client.all :conditions => conditions
Best,
Marnen Laibow-Koser
http://www.marnen.org
[email protected]