I have written scope on modal as below and called ruby class method ‘display_link_query’
scope :data, -> { select("id,#{display_link_query} as display_link
.references( :users )
}
While run brakeman command give sql injection warning.
How to avoid this and any other way to call ruby method in rails scope query ?
def self.display_link_query
“(
CASE
WHEN (number IN (#{Model.numbers[:tested]}, #{Model.numbers[:not_tested]}))
THEN true
ELSE
false
END
)”
end
4
To avoid SQL injection warnings and ensure safe querying in Rails, it’s important to use ActiveRecord’s parameterized queries and avoid interpolating directly into SQL strings. If you need to call a Ruby method within a scope, you should ensure that the method doesn’t introduce SQL injection vulnerabilities.
Using ActiveRecord::Base.sanitize_sql
for Safe SQL Queries
ActiveRecord::Base.sanitize_sql can help to sanitize your SQL fragments, ensuring they are safe from injection.
class YourModel < ApplicationRecord
scope :data, -> {
sanitized_query = ActiveRecord::Base.sanitize_sql([display_link_query])
select("id, #{sanitized_query} AS display_link").references(:users)
}
end