2013-03-14 21 views
0

我可能在這裏做了一些愚蠢的事 - 我可以用其他方式做 - 但我試圖根據計算的字段來訂購我的結果集:使用Rails和Squeel對複雜條件排名的結果

Client.select{['clients.*', 
       (cast((surname == matching_surname).as int) * 10 + 
       cast((given_names == matching_given_names).as int) + 
       cast((date_of_birth == matching_date_of_birth).as int).as(ranking)]}. 
     where{(surname =~ matching_surname) | 
      (given_names =~ matching_given_names) | 
      (date_of_birth == matching_date_of_birth)}. 
     order{`ranking`.desc} 

我的問題是,date_of_birth可能是零。這會導致cast((...).as int)調用返回三個不同的值 - 1如果表達式評估爲true; 0如果表達式評估爲false;如果底層列值爲nil,則返回nil

從表達的nil值導致整個排名,以評估NIL - 這意味着即使我有一個是完全匹配的surnamegiven_names,如果date_of_birthnil戰績,ranking備案是nil

我試圖在其檢查if not nil or the matching_valuecast使用複雜的表達,但它未能使用|一個Squeel例外,並使用||or當紅寶石計算它。

我也試過在爲了使用謂詞別名列:

order{[`ranking` != nil, `ranking`.desc]} 

而是拋出一個異常ActiveRecord抱怨說,列ranking不存在。

我在我的繩索末端...任何想法?

回答

0

有點舞后,我就能夠使用一系列外部的連接到其他範圍如下計算ranking

def self.weighted_by_any (client) 
    scope = 
    select{[`clients.*`, 
      [ 
      ((cast((`not rank_A.id is null`).as int) * 100) if client[:social_insurance_number].present?), 
      ((cast((`not rank_B.id is null`).as int) * 10) if client[:surname].present?), 
      ((cast((`not rank_C.id is null`).as int) * 1) if client[:given_names].present?), 
      ((cast((`not rank_D.id is null`).as int) * 1) if client[:date_of_birth].present?) 
      ].compact.reduce(:+).as(`ranking`) 
      ]}.by_any(client) 

    scope = scope.joins{"left join (" + Client.weigh_social_insurance_number(client).to_sql + ") AS rank_A ON rank_A.id = clients.id"} if client[:social_insurance_number].present? 
    scope = scope.joins{"left join (" + Client.weigh_surname(client).to_sql + ") AS rank_B on rank_B.id = clients.id"} if client[:surname].present? 
    scope = scope.joins{"left join (" + Client.weigh_given_names(client).to_sql + ") AS rank_C on rank_C.id = clients.id"} if client[:given_names].present? 
    scope = scope.joins{"left join (" + Client.weigh_date_of_birth(client).to_sql + ") AS rank_D on rank_D.id = clients.id"} if client[:date_of_birth].present? 
    scope.order{`ranking`.desc} 
end 

其中Client.weigh_<attribute>(client)是另一個範疇,看起來像以下:

def self.weigh_social_insurance_number (client) 
    select{[:id]}.where{social_insurance_number == client[:social_insurance_number]} 
end 

這讓我可以從nil的檢查中突破比較值,因此刪除了布爾計算中的第三個值(TRUE => 1,FALSE => 0)。

清潔?高效?優雅?也許不......但工作。新的信息:)

編輯基地

我這個重構到的東西更漂亮,這要歸功於Bigxiang's answer。以下是我想到的:

首先,我用0123代替示波器。我之前發現,您可以在示波器的select{}部分使用篩選器 - 我們將在一分鐘內使用它。

sifter :weigh_social_insurance_number do |token| 
    # check if the token is present - we don't want to match on nil, but we want the column in the results 
    # cast the comparison of the token to the column to an integer -> nil = nil, true = 1, false = 0 
    # use coalesce to replace the nil value with `0` (for no match) 
    (token.present? ? coalesce(cast((social_insurance_number == token).as int), `0`) : `0`).as(weight_social_insurance_number) 
end 

sifter :weigh_surname do |token| 
    (token.present? ? coalesce(cast((surname == token).as int), `0`) :`0`).as(weight_surname) 
end 

sifter :weigh_given_names do |token| 
    (token.present? ? coalesce(cast((given_names == token).as int), `0`) : `0`).as(weight_given_names) 
end 

sifter :weigh_date_of_birth do |token| 
    (token.present? ? coalesce(cast((date_of_birth == token).as int), `0`) : `0`).as(weight_date_of_birth) 
end 

那麼,讓我們用篩子來衡量我們的所有標準創建範圍:

def self.weigh_criteria (client) 
    select{[`*`, 
      sift(weigh_social_insurance_number, client[:social_insurance_number]), 
      sift(weigh_surname, client[:surname]), 
      sift(weigh_given_names, client[:given_names]), 
      sift(weigh_date_of_birth, client[:date_of_birth]) 
     ]} 
end 

現在,我們就可以判斷是否符合規定的匹配列值,我們計算我們使用排名另一個篩子:

sifter :ranking do 
    (weight_social_insurance_number * 100 + weight_surname * 10 + weight_date_of_birth * 5 + weight_given_names).as(ranking) 
end 

並將它們加在一起使我們的作用域包括所有模型屬性和我們的個計算屬性:

def self.weighted_by_any (client) 
    # check if the date is valid 
    begin 
    client[:date_of_birth] = Date.parse(client[:date_of_birth]) 
    rescue => e 
    client.delete(:date_of_birth) 
    end 

    select{[`*`, sift(ranking)]}.from("(#{weigh_criteria(client).by_any(client).to_sql}) clients").order{`ranking`.desc} 
end 

所以,我現在可以搜索客戶端,並且具有通過排名的結果,他們如何密切配合所提供的標準有:

irb(main): Client.weighted_by_any(client) 
    Client Load (8.9ms) SELECT *, 
           "clients"."weight_social_insurance_number" * 100 + 
           "clients"."weight_surname" * 10 + 
           "clients"."weight_date_of_birth" * 5 + 
           "clients"."weight_given_names" AS ranking 
         FROM (
          SELECT *, 
            coalesce(cast("clients"."social_insurance_number" = '<sin>' AS int), 0) AS weight_social_insurance_number, 
            coalesce(cast("clients"."surname" = '<surname>' AS int), 0) AS weight_surname, 
            coalesce(cast("clients"."given_names" = '<given_names>' AS int), 0) AS weight_given_names,   0 AS weight_date_of_birth 
          FROM "clients" 
          WHERE ((("clients"."social_insurance_number" = '<sin>' 
            OR "clients"."surname" ILIKE '<surname>%') 
            OR "clients"."given_names" ILIKE '<given_names>%')) 
          ) clients 
         ORDER BY ranking DESC 

清潔,更優雅,和工作更好!