1

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?

Valdis Azamaris
  • 1,433
  • 5
  • 22
  • 47

2 Answers2

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

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

Reck
  • 7,966
  • 2
  • 20
  • 24
  • hm to strange by me: but i need to do one array of all currency_list_id without putting it in condition... so last 2 for every currency_list_id in db – Valdis Azamaris Apr 12 '13 at 21:31
  • Ah, I think you might find group_by useful then :). See http://stackoverflow.com/questions/7302992/rails-activerecord-group-results-into-sub-collections-by-date for a good example. – Reck Apr 12 '13 at 21:45
0

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?

Community
  • 1
  • 1
Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90