我在Rails中有一个查询,它根据一系列OR语句获取一组记录。
@properties = policy_scope(Property).withdrawn_query(@hotlist_preference.withdrawn?)
.or(policy_scope(Property).fallen_through_query(@hotlist_preference.fallen_through?))
.or(policy_scope(Property).time_on_market_query(@hotlist_preference.time_on_market?))
.includes(:listings).paginate(page: params[:page], per_page: 20)
基本上有3个查询,更简单的版本可能如下所示:
@properties = Property.where(state = withdrawn).or(where(state = fallen_through)).or(where(age = 4.weeks.ago))
我想要做的是按每个结果满足的OR条件数来订购此查询。所以说有一个属性已经退出并且它的年龄是2周前,它的订单值为2.如果可能的话我还想将订单值添加到返回的属性哈希中,所以我可以使用它在视图中。
我一直在努力找到一种干净的方式来做到这一点,而不是通过同一组查询再次运行结果。
答案 0 :(得分:0)
这看起来非常脏但只能实现这个目标
@properties = Property.where(state = withdrawn).or(where(state = fallen_through)).or(where(age = 4.weeks.ago)).order('case when properties.state = 'withdrawn' && properties.state = 'fallen_through' && properties.age = 'your date' then 10 when hen properties.state = 'withdrawn' && properties.state = 'fallen_through' then 9 when properties.state = 'fallen_through' && properties.age = 'your date' then 9 when properties.state = 'withdrawn' && properties.age = 'your date' then 9 when properties.state = 'withdrawn' && properties.state = 'fallen_through' && properties.age = 'your date' then 10 when properties.state = 'withdrawn' then 8 when properties.state = 'fallen_through' then 8 when properties.age = 'your date' then 8 else 0 end)