2012-06-04 30 views
0

存在PARAMS這是我想要做什麼:檢查是否在軌

我有這樣一段代碼:

customer = Customer.find(:first, :conditions => {:siteId => params[:siteId], :customerCode => params[:id]}) 

如果:customerCode是空的,我想使用:臨時代碼。但我不知道如何。 在此先感謝。

+1

'如果(PARAMS [:編號] )'檢查參數id是否存在。 – xdazz

+0

你在客戶代碼中使用params [:id]如果params id爲null,那麼你會用什麼來代替params [:id]用於臨時代碼? –

+0

@xdazz:'params.has_key? :id'會更好,因爲這正是你的意思。 –

回答

0

我敢肯定你想使用COALESCE數據庫裏面:

customer = Customer.where(:siteId => params[:siteId]) 
        .where('coalesce(customercode, temporarycode) = ?', params[:id]) 
        .first 

的SQL COALESCE函數返回第一個它的參數不是NULL。例如:

coalesce(column1, column2) 

給你column1如果column1不爲NULL和column2如果column1爲NULL。


如果您使用Rails2那麼這樣的事情應該工作:

Customer.find(:first, :conditions => [ 
    'siteid = ? and coalesce(customercode, temporarycode) = ?', 
    params[:siteId], params[:id] 
]) 
+1

它取決於你是否使用SQL db –

+0

@Sagiv:true,但這是一個非常安全的假設,除非另有說明。 –

+0

.where在rails 2中不可用。所以我嘗試了這個: –

1
customer = Customer.find_by_siteid_and_customercode params[:siteId], params[:id] 
customer ||= Customer.find_by_siteid_and_temporarycode params[:siteId], params[:id] 

利用發現者是最安全,更清潔