在项目创建时为了逻辑上的简单,采用了多级子表嵌套;而且底层子表大多是静态表,即没有用has_one或belongs_to作为相互关系的.
在某个对象的搜索涉及到3个底层子表中的字段的比较,很难用where或find_by_sql方法,遂先用纯sql语句写了个查询:
select r.*,tmp1.value from (select re.risk_id,tmp0.value from (select rl.risk_evaluate_id,rln.value from risk_levels rl inner join risk_level_names rln on rln.id = rl.risk_level_name_id) as tmp0 inner join risk_evaluates re on tmp0.risk_evaluate_id = re.id) as tmp1 inner join risks r on tmp1.risk_id = r.id
共有7个查询项,最深子表深度为3层,用pgAdmin查询结果如下:
我们可以直接在rails console中做测试:
ActiveRecord::Base.connection.execute("select r.id,tmp.degree from (SELECT re.risk_id as risk_id,rl.degree as degree FROM risk_evaluates re inner join risk_levels rl on rl.risk_evaluate_id = re.id) AS tmp inner join risks r on tmp.risk_id = r.id")
查询结果为hash数组,key为查询字段名.但是没法和其他条件混合起来使用,所以还是用map来做:
if @risks.count != 0 && risk_level_name_id != "-1"
@risks = @risks.select do |risk|
eval("risk.risk_evaluate.risk_level.risk_level_name.value " + risk_operator + "RiskLevelName.find(risk_level_name_id).value")
end
end
但是数组有个问题,就是无法分页,will_paginate自从3.0版本后默认只能在ActiveRecord::Relation上分页.但是你可以手动开启在数组上的分页功能.
在项目config/initializers路径下新建一个rb文件,比如paginate_on_array.rb,内容如下:
require 'will_paginate/array'