我正在做手册join
,我需要将参数传递给它的ON
子句:
Foo.joins("LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.baz = #{baz}")
有没有办法将baz
作为参数传递,以避免潜在的注射问题?有一种方法sanitize_sql_array
,但在这种情况下我不确定如何使用它。
注意:我不能使用where
,因为它不一样。
答案 0 :(得分:12)
使用sanitize_sql_array,即:
# 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)
尝试过它并且有效。
答案 1 :(得分:10)
活动记录模型具有sanitize
类方法,因此您可以这样做:
Foo.joins("LEFT OUTER JOIN bars ON foos.id = bars.foo_id AND bars.baz = #{Foo.sanitize(baz)}")
__
它已从导轨5.1中移除,使用ActiveRecord::Base.connection.quote()
代替
答案 2 :(得分:0)
Arel可以做到。
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
if (!Settings.canDrawOverlays(this)) {
// You don't have permission
checkPermission();
} else {
// Do as per your logic
}
}
}
这产生
baz = "i am a baz"
foos = Arel::Table.new('foos') # or Foo.arel_table, if this is an AR model
bars = Arel::Table.new('bars')
join = foos.outer_join(bars).on(
foos[:id].eq(bars[:foo_id]),
bars[:baz].eq(baz))
puts join.to_sql
现在,如果您想将其返回到ActiveRecord查询中,而不仅仅是打印SQL:
SELECT FROM "foos"
LEFT OUTER JOIN "bars" ON
"foos"."id" = "bars"."foo_id"
AND "bars"."baz" = 'i am a baz'
答案 3 :(得分:-3)
我认为你应该这样试试:
Foo.joins("LEFT OUTER JOIN bars ON foo.id = bars.foo_id AND bars.baz = ?", baz)
有更多参数:
Foo.joins("LEFT OUTER JOIN bars ON foo.id = ? AND bars.baz = ? AND ...", foo, baz, etc...)
答案 4 :(得分:-4)
如果您传递值的哈希值,那么您应该是安全的,AR会保护您免受SQL注入,如下所示:
Foo.joins("LEFT OUTER JOIN bars ON foo.id = bars.foo_id").where(bars: {baz: baz})
不要在sql中使用易受sql注入攻击的行字符串。