0

これが私がやりたいことです:

私はこのコードを持っています:

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

:customerCodeがnullの場合、代わりに:temporaryCodeを使用したいと思います。しかし、私は方法がわかりません。前もって感謝します。

4

2 に答える 2

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

ファインダーを使用することは、最も安全でクリーンです

于 2012-06-04T07:04:16.827 に答える
0

データベース内でCOALESCEを使用したいと確信しています:

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

SQL COALESCE 関数は、NULL ではない最初の引数を返します。例えば:

coalesce(column1, column2)

column1if column1is not NULL とcolumn2if is NULL を返しますcolumn1


Rails2 を使用している場合は、次のように動作するはずです。

Customer.find(:first, :conditions => [
    'siteid = ? and coalesce(customercode, temporarycode) = ?',
    params[:siteId], params[:id]
])
于 2012-06-04T06:21:20.937 に答える