2014-10-19 50 views
0

我有以下的鍵串,其中列1代表值,列2是分數,列3是鍵串。 第2列是通過檢查keystring中的column1值來計算的。執行條件where子句使用Arel表

如果列-1值是7,那麼它是小於25。所以,第2列的值將爲0。

enter image description here

爲了實現這一點,我提出UPPER_LIMIT和LOWER_LIMIT。

Lower_Limit | Upper Limit 
NULL  | 25 
25   | 75 
75   | 125 
125   | 250 
250   | 500 
500   | NULL 

現在用下面的查詢:

score_line_item = Model.where("upper_limit > ? AND lower_limit <= ?", value, value) 
score_line_item = Model.where("upper_limit IS null AND lower_limit >= ? ", value) unless score_line_item.present? 
score_line_item = Model.where("lower_limit IS null AND upper_limit > ? ", value) unless score_line_item.present? 

如何使用Rails這樣,我實現了相同的? (可能在1行)。我無法刪除重複的行。我正在尋找上述問題的更好的解決方案,即使它與Arel表一樣。

回答

1

只是SQL合併或

score_line_item = Model.where(
        "upper_limit > :value AND lower_limit <= :value OR upper_limit IS null AND lower_limit >= :value OR lower_limit IS null AND upper_limit > :value ", 
        {value: value} 
       ) 

也做這方面的需求是SQL?你能不能在Ruby中做到這一點?

# Usage: credit_scoring(35) #=> 1 
def credit_scoring(value) 
    [25, 75, 125, 250, 500].count do |lower_bound| 
    lower_bound <= value 
    end 
end