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?
To retrieve last N records :
Quarter.last(n).reverse
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With