检查参数是否存在于轨道中



这就是我想做的:

我有这段代码:

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

如果 :customerCode 为空,我想改用 :temporaryCode。但我不知道怎么做。提前谢谢。

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

使用查找器更安全,更清洁

我很

确定你想在数据库中使用 COALESCE:

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

SQL COALESCE 函数返回其第一个非 NULL 的参数。例如:

coalesce(column1, column2)

如果column1不是 NULL,则为您提供column1,如果column1为 NULL,则提供column2


如果你使用的是 Rails2,那么这样的东西应该可以工作:

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

最新更新