RAILS 4 ACTIVERECORD按键检索最新记录

时间:2014-08-08 17:39:00

标签: ruby-on-rails ruby postgresql activerecord

我的数据库(PostgreSQL)中有一个表,大致如下:

Currency    Rate    Created_at
USD         13.5    08/07/2014
EURO        18.5    08/07/2014
USD         13.3    08/08/2014
EURO        18.3    08/08/2014
USD         13.4    08/06/2014
EURO        18.4    08/06/2014
USD         13.7    08/05/2014
EURO        18.7    08/05/2014

我想要做的只是获取每个货币键的最新值('USD','EURO') 在此示例中,预期结果为:

USD         13.3    08/08/2014
EURO        18.3    08/08/2014

我尝试过:

BancomerTasa.order(:created_at).select("DISTINCT ON (divisa) *")
ActiveRecord::StatementInvalid: PG::InvalidColumnReference: 
ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions
(ERROR)

BancomerTasa.uniq.pluck(:divisa, :tasa)
(1.1ms)  SELECT DISTINCT "bancomer_tasas"."divisa"
, "bancomer_tasas"."tasa" FROM    "bancomer_tasas"
 => [["EURO", #<BigDecimal:7fd4941d66c0,'0.1812E2',18(18)>], 
    ["DOLAR", #<BigDecimal:7fd4941d64e0,'0.1352E2',18(18)>],
    ["DOLAR", #<BigDecimal:7fd4941d62d8,'0.1356E2',18(18)>], 
    ["EURO", #<BigDecimal:7fd4941d6148,'0.1814E2',18(18)>]]
(TOO MANY VALUES)

BancomerTasa.group(:id,:divisa).having('created_at = MAX(created_at)')    
(GROUPING BY ID MAKES NO SENSE TO ME SINCE THAT'S THE PK 
BUT IF I DON'T I GET THIS ERROR: 
PG::GroupingError: ERROR:  column "bancomer_tasas.id" 
must appear in the GROUP BY clause or be used in an aggregate function)

我觉得我现在有点困惑。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

要获取每种货币的最新BancomerTasa记录,请使用where添加正确货币的条件,{_ 1}} by created_at,并获取order记录:

last