2017-04-24 72 views
1

我想基于SQL查询来写一个方法,这是我写到目前为止Rails的可能的SQL注入错误

class Hospital 
    class Doctors < ActiveRecord::Base 

    self.table_name = 'vDoctorDetails' 

def self.doctor_status(user_id) 

     doctor_department = ActiveRecord::Base.connection.quote('Abc') 
     doctor_status = ActiveRecord::Base.connection.quote('Y') 

    Doctors 
    .select('vDoctorDetails.DoctorInfo') 
    .where("vDoctorDetails.doctor_id = #{user_id}"} 
    .where("vDoctorDetails.doctor_department = #{doctor_department}"} 
    .where("vDoctorDetails.doctor_status = #{doctor_status}"} 
    .first 
    end 
    end 
    end 

我被胖模型,瘦控制器的概念,因此创建模型这种方法去。当我在控制台测试此它工作正常,但是当我试图把它部署到GitHub的主分支,司闸员亲抛出错误

sql injection found near   .select('vDoctorDetails.DoctorInfo') 
     .where("vDoctorDetails.doctor_id = #{user_id}"} 

我试图创建范围,但随后我将不得不调用所有范围的控制。什么是写这个方法的最好方法,所以我可以摆脱sql注入错误?

回答

2

尝试:

Doctors 
.select('vDoctorDetails.DoctorInfo') 
.where('vDoctorDetails.doctor_id = ?', user_id) 
.where('vDoctorDetails.doctor_department = ?', doctor_department) 
.where('vDoctorDetails.doctor_status = ?', doctor_status) 
.first 
+0

谢谢苏珊。这工作 – user938438932

0

您可以重写整个这样的查询

def self.doctor_status(user_id) 
    where(doctor_id: user_id, doctor_department: 'Abc', doctor_status: 'Y') 
    .select('DoctorInfo') 
    .first 
end 

和Rails将采取的正确引用值并添加表名护理。

阅读Rails指南中的query syntax and hash conditions