2010-12-03 34 views
0

我有一個用於過濾查詢的表單。某些表單屬性是可選的;我只是想知道如何將它們附加爲主動記錄條件,如果(且僅當)它們具有設定值時?Rails新手:在activerecord中添加條件?

其中有相當一部分人,所以我寧願不對每種潛在價值模式進行單獨查詢。有什麼建議麼?

舉一個具體的例子:

people = People.paginate(
    :all, 
    :include => [:people_postcodes, :people_specialties, :people_states], 
    :conditions => ["people_specialties.people_type_id = %s AND (people_postcodes.postcode_id = %s OR people_states.state_id = %s)" % [self.people_type_id, postcodeid.id, stateid]], 
    :page => page, 
    :per_page => 16 
) 

我將如何最好的去創造只有在可選的「國籍」屬性填充一個額外的條件(說「國籍」)?

回答

2

首先,你的條件有點不安全。你正在做基本的ruby文本替換,這會讓站點用戶注入他們想要的任何惡意的sql。相反,格式化如下:

people = People.paginate(
    :all, 
    :include => [:people_postcodes, :people_specialties, :people_states], 
    :conditions => ["people_specialties.people_type_id = ? AND (people_postcodes.postcode_id = ? OR people_states.state_id = ?)", self.people_type_id, postcodeid.id, stateid], 
    :page => page, 
    :per_page => 16 
) 

要回答你的問題,沒有自然的方法來處理Rails 2.x中的另一個條件。我會這樣做:

conditions = ["people_specialties.people_type_id = ? AND (people_postcodes.postcode_id = ? OR people_states.state_id = ?)", self.people_type_id, postcodeid.id, stateid] 

if params[:nationality] 
    conditions.first += " and nationality = ?" 
    conditions.push params[:nationality] 
end 

people = People.paginate(
    :all, 
    :include => [:people_postcodes, :people_specialties, :people_states], 
    :conditions => conditions, 
    :page => page, 
    :per_page => 16 
) 

在上面的例子中,我假設國籍作爲參數傳入,但根據需要進行調整。我創建了原始條件數組,然後追加第一個元素(實際條件字符串)並在數組的末尾添加一個元素:國籍值。

我希望這有助於!

+0

+1爲SQL注入信息。希望那裏有一個叫做「危險代碼」的標籤(?),以便新手(和一些老年人)知道代碼是「危險的」。 – Zabba 2010-12-03 06:02:38

相關問題