If a query can't be efficiently expressed using ActiveRecord, how to safely use ActiveRecord::Base.connection.execute
when interpolating passed params
attributes?
如果使用ActiveRecord无法有效表达查询,那么在插入传递的params属性时如何安全地使用ActiveRecord :: Base.connection.execute?
connection.execute "... #{params[:search]} ..."
2 个解决方案
#1
10
You can use the methods in ActiveRecord::Sanitization::ClassMethods.
您可以使用ActiveRecord :: Sanitization :: ClassMethods中的方法。
You do have to be slightly careful as they are protected and therefore only readily available for ActiveRecord::Base
subclasses.
您必须要小心谨慎,因为它们受到保护,因此只能用于ActiveRecord :: Base子类。
Within a model class you could do something like:
在模型类中,您可以执行以下操作:
class MyModel < ActiveRecord::Base
def bespoke_query(params)
query = sanitize_sql(['select * from somewhere where a = ?', params[:search]])
connection.execute(query)
end
end
You can send
the method to try it out on the console too:
你也可以发送方法在控制台上试用它:
> MyModel.send(:sanitize_sql, ["Evening Officer ?", "'Dibble'"])
=> "Evening Officer '\\'Dibble\\''"
#2
2
ActiveRecord has a sanitize method that allows you to clean the query first. Perhaps it's something you can look into: http://apidock.com/rails/v4.1.8/ActiveRecord/Sanitization/ClassMethods/sanitize
ActiveRecord有一个清理方法,允许您首先清理查询。也许这是你可以研究的东西:http://apidock.com/rails/v4.1.8/ActiveRecord/Sanitization/ClassMethods/sanitize
I'd be very careful inserting parameters directly like that though. What problem are you experiencing, that you cannot use ActiveRecord?
我会非常小心地直接插入参数。你遇到什么问题,你不能使用ActiveRecord?
#1
10
You can use the methods in ActiveRecord::Sanitization::ClassMethods.
您可以使用ActiveRecord :: Sanitization :: ClassMethods中的方法。
You do have to be slightly careful as they are protected and therefore only readily available for ActiveRecord::Base
subclasses.
您必须要小心谨慎,因为它们受到保护,因此只能用于ActiveRecord :: Base子类。
Within a model class you could do something like:
在模型类中,您可以执行以下操作:
class MyModel < ActiveRecord::Base
def bespoke_query(params)
query = sanitize_sql(['select * from somewhere where a = ?', params[:search]])
connection.execute(query)
end
end
You can send
the method to try it out on the console too:
你也可以发送方法在控制台上试用它:
> MyModel.send(:sanitize_sql, ["Evening Officer ?", "'Dibble'"])
=> "Evening Officer '\\'Dibble\\''"
#2
2
ActiveRecord has a sanitize method that allows you to clean the query first. Perhaps it's something you can look into: http://apidock.com/rails/v4.1.8/ActiveRecord/Sanitization/ClassMethods/sanitize
ActiveRecord有一个清理方法,允许您首先清理查询。也许这是你可以研究的东西:http://apidock.com/rails/v4.1.8/ActiveRecord/Sanitization/ClassMethods/sanitize
I'd be very careful inserting parameters directly like that though. What problem are you experiencing, that you cannot use ActiveRecord?
我会非常小心地直接插入参数。你遇到什么问题,你不能使用ActiveRecord?