Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parametrized join in Rails 4

I am doing manual join and I need to pass a parameter to its ON clause:

Foo.joins("LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.baz = #{baz}")

Is there a way to pass baz as a parameter, to avoid potential injection problems? There is a method sanitize_sql_array, but I'm not sure how to make use of it in this case.

Note: I can't use where because it's not the same.

like image 713
Mladen Jablanović Avatar asked Feb 25 '16 22:02

Mladen Jablanović


2 Answers

With sanitize_sql_array, that would be:

# Warning: sanitize_sql_array is a protected method, be aware of that to properly use it in your code
ar = ["LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.baz = %s", baz]
# Within foo model:
sanitized_sql = sanitize_sql_array(ar)
Foo.joins(sanitized_sql)

Tried it and it worked.

like image 174
Kulgar Avatar answered Oct 05 '22 22:10

Kulgar


Active record models have sanitize class method, so you could do:

Foo.joins("LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.baz = #{Foo.sanitize(baz)}")

__

It's been removed starting rails 5.1, use ActiveRecord::Base.connection.quote() instead

like image 41
ddgd Avatar answered Oct 06 '22 00:10

ddgd