Question

This is in my controller:

@somethings = Something.find(:all)

And my count variable would display a break up of this data based on 'rca' as such:

@something_to_count = Something.count( :conditions => { :rca => "4X32W"})
@something_to_count2 = Something.count( :conditions => { :rca => "6X36W"})

..... etc to other count variables...

Simple as this is, I was trying to get it to display these stats/counts for all entries made from the 'Something' table within the last thirty days in one view and within a date range in another view. I have the default timestamps added by the scaffold function (created_at and updated_at) in my model.

My view would have to be split up into two pages. One page to accept a date range and display the count variables along with the data in a table and the other page to display just the same for the last thirty days. (i.e. def last_30_days and def within_dates would be the actions). I found a solution on line which has a date variable subtracted from 30 etc which did not seem to work. A full fledged working solution would be greatly appreciated. Please help. Also, how would I convert a simple date range entry into the same format as the datestamps?

Was it helpful?

Solution

You can create scopes to your querys, so you can reuse them.
My approach to your problem would be something like this:

scope :last_30_days, where("created_at between ? and ?", Date.today - 30, Date.today)
scope :within_dates, lambda { |start_date, end_date|
  where("created_at between ? and ?", start_date, end_date)
}
scope :based_on_rca, lambda { |rca|
  where(:rca => rca)
}

@something_to_count = Something.based_on_rca("4X32W").last_30_days.count
@something_to_count = Something.based_on_rca("4X32W").within_dates(Date.today - 4.month, Date.today - 1.month).count

Various scopes with small queries that can be chained to reflect on a larger one. Regards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top