2017-04-24 68 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