Rails group records by month using db query - ruby-on-rails

Hi I am trying to find a simple way to expand my db query and group the records shown by month (Ideally I would like next month stored in "Next Page"). Is there a way to do this?
Current query
#submissions = Submission.where(:Desired_Location => current_agent.Company_Business_Location)
Thanks

First get month name from your date field and then use group method to group by month
#submissions = Submission.where(:Desired_Location => current_agent.Company_Business_Location).group('strftime('%m', your_date_field)')
In your case I would suggest to group by year as well. In that case use this:
#submissions = Submission.where(:Desired_Location => current_agent.Company_Business_Location).group('strftime('%Y %m', your_date_field)')

Related

How compare time range using created_at fields on rails

I need to get the records only included on time range using default created_at Rails field. No matters the day was created.
I have this:
#start_time = test.start_time.strftime("%I:%M%p")
#end_time test.end_time.strftime("%I:%M%p")
#websites = device.websites.where(:created_at => #start_time..#end_time)
I was searching for something like this:
#websites = device.websites.where(:created_at::time => #start_time..#end_time)
This generate this SQL sentence without results.
SELECT DISTINCT `websites`.* FROM `websites` WHERE `websites`.`device_id` = 2 AND (`websites`.`created_at` BETWEEN '16:10:00' AND '21:10:00')
But if I add time function to created_at field, works fine.
SELECT DISTINCT `websites`.* FROM `websites` WHERE `websites`.`device_id` = 2 AND (time(`websites`.`created_at`) BETWEEN '16:10:00' AND '21:10:00')
How is the best Rails way to do this ?
Rails automatically converts the time objects to the format that your database requires, so there is no need for strftime. You should be able to do it like this:
#websites = device.websites.where(:created_at => test.start_time..test.end_time)

activerecord comparing times

i am trying to do a query that will be compare the time stored in the database to the current time, and if it is greater than today to display those records.
below is query i am currently using that isnt displaying any records
#schedules = Schedule.where(:team_id => current_user[:team_id], :event => '1', :time => ">= Time.now.zone")
how do i go back query against a timestamp? so that these records will be displayed?
have also tried the following
#schedules = Schedule.find_all_by_team_id_and_event_and_time(current_user[:team_id],"1", :time)
#schedules = Schedule.where("team_id = ? and event = ? and time >= ?", [current_user[:team_id], "1", Time.zone.now])
The string is used directly in the SQL query so you need to make sure the column names are correct and unambiguous (if you joined on another table that also has a team_id colum, you would need to do schedules.team_id = ? and ...)

Use active record to find a record by month and day, ignoring year and time

I have a model (Entries) with five years worth of records (one record per day). I need a method that, when passed a date object such as 2011-12-25 00:00:00, will show me ALL the records that have happened on 12/25 (querying against the :created_at column), regardless of the year or time that's passed.
RoR 3.0.9 / Ruby 1.9.2p290
You can use the MONTH and DAY values of mysql. Maybe something like:
Model.where("MONTH(created_at) = ? and DAY(created_at) = ?", somedate.month, somedate.day)
A general solution that should work with most SQL databases (include MySQL and PostgreSQL):
Entry.where('extract(month from created_at) = ? AND extract(day from created_at) = ?', d.month, d.day)
SQLite doesn't understand extract though so you'd have to use:
Entry.where("strftime('%m/%d', created_at) = ?", d.strftime('%m/%d'))
Assuming that you are using mysql:
User.where(["DAY(created_at) = ? AND MONTH(created_at) = ?", date.day, date.month])
Assume RDBMS is MySQL and you have form with combobox to select month and/or date_of_months, may be you could make a named_scope, for example :
scope :by_date_or_month, lambda { |date, month| {:conditions => ["DAYOFMONTH(created_at) = ? or MONTH(created_at) = ?", date, month]}}
Test from IRB :
Model.by_date_or_month(31,8)
Model.by_date_or_month(nil,8)

How to use datetime in the condtions of a find/count in Ruby on Rails

I'm trying to count the number of rows in a certain table by datetime.
More specifically, by a certain month, but can't find the right way to
write the conditions for it.
xxx.count(:all, :conditions=> :xxx => yyy)
I have a datetime yyy to compare with xxx, but only want to compare the year and month.
The more efficient way is like this:
range = Date.today.beginning_of_month..Date.today.end_of_month
Model.count(:conditions => {:date_field => range})
This will generate a range condition, which, if you have an index on the date_field will be very fast even for millions of rows.
I have a plugin/gem called by_star which you can install using just sudo gem install by_star if you have gemcutter.org as one of your sources.
This plugin allows you to do this:
Post.by_month("January", :year => 2009)
Which will return all records from the Post model from January 2009.
This might work.
:conditions => ["month(date_field) = ? AND year(date_field) = ?", month, year]

Select, group and sum results from database

I have a database with some fields I'd like to sum. But that's not the big problem, I want to group those fields by the month they were created. ActiveRecord automaticaly created a field named "created_at". So my question; how can I group the result by month, then sum the fields for each month?
Updated with code
#hours = Hour.all(:conditions => "user_id = "+ #user.id.to_s,
:group => "strftime('%m', created_at)",
:order => 'created_at DESC')
This is the code I have now. Managed to group by month, but doesn't manage to sum two of my fields, "mins" and "salary" which I need to sum
You can use active record calculations to do this. Some example code might be
Model.sum(:column_name, :group => 'MONTH("created_at")')
Obviously with the caveat MONTH is mysql specific, so if you were developing on an SQLite database this would not work.
I don't know if there's a SQL query you use to do it (without changing your current table structure). However, you do it with some lines of code.
records = Tasks.find(:conditions => {..})
month_groups = records.group_by{|r| r.created_at.month}
month_groups.each do |month, records|
sum stuff.. blah blah blah..
end
I saw this link on the right side of this question. I assume other databases, besides MySQL have similar functions.
mysql select sum group by date
Fixed it by using :select when getting the query, inputing selects manually
#hours = Hour.all(:conditions => "user_id = "+ #user.id.to_s,
:select => "created_at, SUM(time) time",
:group => "strftime('%m', created_at)",
:order => 'created_at DESC')

Resources