简体   繁体   English

Rails如何按平均价格订购记录

[英]Rails how to order records by average price

I am trying to set the order of records returned by the controller by price. 我试图按价格设置控制器返回的记录顺序。 The problem is that there are 3 different price options and it is possible for just 1 price, 2 prices or all prices to be used on each record. 问题在于,有3种不同的价格选项,并且每个记录可能只使用1个价格,2个价格或所有价格。 So I have decided to set the position by average price. 因此,我决定按平均价格设置头寸。 To get the average price I anticipate taking the sum of available prices and dividing by the available price count. 为了获得平均价格,我希望将可用价格的总和除以可用价格计数。

Currently i'm setting the order by id: 目前,我正在按ID设置订单:

def category
    @manufacturers = Manufacturer.order("manufacturers.id ASC").where(:visible => true)
end

Each record has :hp_price, :ch_price, :mp_price (all monthly payment prices) so I imagine I want to check if each option is set and, if so, add it to an array which I can later run the calculation on (maybe this isn't the best way?). 每个记录都有:hp_price,:ch_price,:mp_price(所有月度付款价格),因此我想我想检查是否设置了每个选项,如果可以,则将其添加到一个数组中,以便以后进行计算(也许是这样)不是最好的方法吗?)。

I am a bit stumped as to how to go about doing this (I'm new to rails). 我对如何执行此操作感到有些困惑(我是Rails的新手)。 Could I do this in-line in the controller? 我可以在控制器中内联吗? (if so should i even do this?) (如果是这样,我什至应该这样做?)

something to the effect of: 具有以下效果:

def category
    @manufacturers = Manufacturer.order((manufacturers.hp_price+manufacturers.ch_price+manufacturers.mp_price)/3 ASC).where(:visible => true)
end

Or another possibility would be to add an average price column to each record and just work it out when the record is created (it feels like that is a bit of an over-the-top solution to me though). 或另一种可能性是在每条记录上添加一个平均价格列,然后在创建记录时就对其进行计算(不过,这似乎对我来说是个过分的解决方案)。

I guess i'd like to know what you would consider best practice in such a situation as, like i said, I am new to this and i'm worried that the solution that I would come up with if I just muddle on through would be a bit hacky! 我想我想知道您在这种情况下会如何考虑最佳实践,就像我说的那样,这是我的新手,我担心如果我继续迷惑我会想到的解决方案会有点hacky!

Refer the columns like this and it should work 引用这样的列,它应该可以工作

def category
  @manufacturers = Manufacturer.order("(hp_price+ch_price+mp_price)/3 asc").where(:visible => true)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM