问题描述
|
我正在尝试从关联中选择列计数,但它似乎不起作用。这是我的代码:
scope :search,lambda { |search,order_Syntax|
select(\"*,COUNT(payment_notifications.p_type) AS number_of_objects\")
{
:conditions =>
[\'items.title LIKE ? OR items.desc LIKE ? OR taggings.context LIKE ?\',\"%#{search}%\",\"%#{search}%\"],:include => [:taggings,:payment_notifications,:user],:order => \'number_of_objects\'
}
}
我想要实现的是:
我想按购买数量订购。因此,假设这是我的payment_notifications表:
item_id | p_type
2 | \'付款\'
2 | \'付款\'
6 | \'付款\'
2 | \'付款\'
3 | \'付款\'
6 | \'付款\'
无| \'退出\'
顺序应为:
2
6
3
希望你能理解。
提前致谢。
解决方法
找到了我的解决方案。需要使用计数器缓存。感谢大家!
, 您还应该在订单块中包含itme_id
:order => \'item_id,number_of_objects\'
, 首先,您应该使用普通方法而不是范围,因为查询相当复杂,并且结果将完全相同(更易于格式化)。
其次,我不确定为什么不在任何地方都使用lambda中的参数“ order_syntax”。
这是我的建议(使用新的Active Record链接语法)。我尚未测试过,但如果我理解您的原始查询,它应该可以工作。
def search(term)
select(\"*,COUNT(payment_notifications.p_type) AS number_of_objects\").
where(\'items.title LIKE ? OR items.desc LIKE ? OR taggings.context LIKE ?\',\"%#{term}%\",\"%#{term}%\").
includes(:taggings,:payment_notifications,:user).
order(\'number_of_objects\')
end