Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3- Retrieve last N records

I have a model that collects financial data from my clients each calendar quarter of each year (so :quarter 1, 2, 3, and 4 for any given :year). For simplicity, the model is called Quarter and has :client_id, :quarter, :year, and :amount attributes. I want to be able to query and display the last four entries for the :amount attribute based on the quarter that is currently being displayed.

So for example, if I'm looking at :quarter 3 for :year 2011, then I want to show the :amount for the current quarter (which is easy), as well as the :amount for :quarter 2 & 1 for :year 2011, and :quarter 4 for :year 2010. Does that make sense?

I made this work by assigning a different variable to each record that I want to retrieve, then using elsif statements to find it, but I know there has to be a cleaner way to do it.

How do I do this?

like image 369
FattRyan Avatar asked Oct 09 '11 17:10

FattRyan


2 Answers

To retrieve last N records :

Quarter.last(n).reverse
like image 161
Noémien Kocher Avatar answered Sep 25 '22 06:09

Noémien Kocher


with the Rails 2.x query interface the answer is:

Quarter.find(:all, :order => :year, :limit => 4).reverse

with the Rails 3.x query interface the answer is:

Quarter.order(:by => :year).limit(4).reverse

btw. I think you should not store your data in a model called "Quarter" , but rather in a model called "FinancialData" and have that model have an attribute "quarter" which would contain 2011/1, 2011/2, or havt two attributes :year and :quarter which need to be indexed together

See also:

http://guides.rubyonrails.org/active_record_querying.html

http://m.onkey.org/active-record-query-interface

like image 45
Tilo Avatar answered Sep 25 '22 06:09

Tilo