问题:RAILS 4 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)

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

解答

要获取每种货币的最新BancomerTasa记录,请使用where添加正确货币的条件,orderby created_at,并获取last记录:

most_recent_usd = BancomerTasa.where(currency: 'USD').order(:created_at).last
most_recent_euro = BancomerTasa.where(currency: 'EURO').order(:created_at).last
Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐