byCoder
byCoder

Reputation: 9184

Rails fetch row with latest update

I have such db table structure:

id | currency_list_id | direction_id | value | updated_at

and i have such data:

1 | 1 | 1 | 8150 | 09-08-2010 01:00:00
1 | 1 | 2 | 8250 | 09-08-2010 01:00:00
1 | 2 | 1 | 8150 | 06-08-2010 01:00:00
1 | 2 | 2 | 8150 | 06-08-2010 01:00:00
1 | 1 | 1 | 8150 | 09-08-2010 15:00:00
1 | 1 | 2 | 8250 | 09-08-2010 15:00:00

so currency in exchanger is setted almost everyday, and could be setted more than one time in a day.... but also one could be setted some days ago... And i must to fetch all actual data..

How in rails (ruby) i could fetch only last actual data?

In my example result will be:

1 | 2 | 1 | 8150 | 06-08-2010 01:00:00
1 | 2 | 2 | 8150 | 06-08-2010 01:00:00
1 | 1 | 1 | 8150 | 09-08-2010 15:00:00
1 | 1 | 2 | 8250 | 09-08-2010 15:00:00

how to do this?

i try so:

@currencies = CurrencyValue.find(:all, :conditions => {:currency_list_id => id}, :order => :updated_at)

but then i will fetch all data for some currency_list_id with ordering, but how to fetch only last 2 values? How to fetch last 2 ordered rows?

Upvotes: 0

Views: 222

Answers (2)

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17516

I think what you need by be a GROUP_BY. There's another question that explains it here:

How to get the latest record in each group using GROUP BY?

Upvotes: 0

Reck
Reck

Reputation: 8772

@currencies = CurrencyValue.find(:all, :conditions => {:currency_list_id => id, :order => :updated_at}).last(2)

I think :). Can't check this right now.

Upvotes: 1

Related Questions