0

这就是我想做的:

我有这段代码:

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

如果 :customerCode 为空,我想改用 :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]

使用finder更安全、更清洁

于 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 column1is NULL。


如果您使用的是 Rails2,那么这样的事情应该可以工作:

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