0

我可能在这里做一些愚蠢的事情 - 我对其他方式持开放态度 - 但我试图根据计算字段对我的结果集进行排序:

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- 这意味着即使我有一条与 完全匹配的记录,surname并且given_names如果date_of_birth列是nilranking则记录的 是nil

我曾尝试在castthat 检查中使用复杂的表达式if not nil or the matching_value,但是使用时它会因 Squeel 异常而失败,|并且 ruby​​ 在使用||and时会对其进行评估or

我还尝试按别名列的顺序使用谓词:

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

但这会引发ActiveRecord异常,抱怨该列ranking不存在。

我走投无路了……有什么想法吗?

4

1 回答 1

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

whereClient.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 的回答,我已将其重构为更漂亮的东西 。这是我想出的:

首先,我weigh_<attribute>(client)用筛子替换了范围。我之前发现您可以在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

更干净、更优雅、更好用!

于 2013-05-24T15:07:52.563 回答