【问题标题】:ActiveRecord Order by Number of Conditions MatchedActiveRecord 按匹配条件数排序
【发布时间】:2017-09-01 04:39:30
【问题描述】:

我在 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。如果可能的话,我还想将订单值添加到返回的属性哈希中,这样我就可以使用它在视图中。

我一直在努力寻找一种干净的方法来执行此操作,而无需再次通过一组相同的查询运行结果。

【问题讨论】:

  • 你用的是什么数据库?
  • 我不知道 ActiveRecord 是否支持此功能,但您可以考虑使用raw SQL 来实现此功能吗?
  • 我正在使用 PostgreSQL

标签: sql ruby-on-rails activerecord


【解决方案1】:

这看起来很脏,但这是实现这一目标的唯一方法

@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)

【讨论】:

  • 我将您的订单声明进一步整理了一下。因为我认为我可以这样做:(条件 1 时的情况下 1 否则 0 结束 + 情况时条件 2 时的情况下 1 否则 0 结束 + 情况时条件 3 时的情况下 1 否则 0 结束)
  • 是的,这更干净了。
猜你喜欢
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多