2011-04-24 42 views
1

給SQLite中以下(已經簡化的)查詢:Rails3/ActiveRecord:選擇和參數?

def self.calculate(year, month, user_id, partner_id) 
    where(':user_id = entries.user_id OR :partner_id = entries.user_id', {  
     :user_id => user_id, 
     :partner_id => partner_id 
    }). 
    where('entries.date <= :last_day', { 
     :last_day => Date.new(year, month, 1).at_end_of_month 
    }). 
    select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {  
     :user_id => user_id 
    }). 
    group("strftime('%Y-%m', date)") 
end 

完整的查詢有更多的資金與不同情況下的語句,其中一些依賴於它是否是USER_ID奧德PARTNER_ID。不幸的是,Rails抱怨說,select並沒有像第二個參數那樣使用替換。有沒有辦法實現我想要的而不運行兩個查詢,一個用於user_id,另一個用於partner_id?

回答

-1

一個可以如此盲目....代替:

select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {  
    :user_id => user_id 
}). 

只是生成字符串:

select('sum(case when joint = "f" and user_id = ' + user_id.to_s + ' then amount_calc else 0 end) as sum_single'). 

由於沒人接,這是檔案:)

編輯:對不起,小心:如下所述,這是脆弱的。

+0

如果我沒有弄錯,單引號的字符串沒有插值,所以你必須在雙引號中包含選擇以使替換工作。 – 2013-04-02 17:55:27

+3

這可以用作SQL注入攻擊向量,例如,如果user_id被傳入爲'; DROP TABLE USERS; - '你可能會丟掉桌子。所以在做這件事時要特別小心,它可能會非常糟糕。 – Rtype 2014-08-14 06:16:51