activerecord comparing times - ruby-on-rails

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 ...)

Related

How to merge multiple and different ActiveRecord query in rails and paginate over the records?

I have two similar tables in rails named as messages and message_histories. Periodically we remove the old data from messages table and drop it in message_histories .
Now , I want to generate a report on the count of messages grouped by app_id which is present in message and message_history table .
Is there a way to Query [Message & MessageHistory ] Model and paginate on the records .
Currently I use the following Step , It looks weird but suggest a better way to do this :
#messages = Message.select("SUM(devices_count) as count ,CAST(run_at AS DATE) AS date").where(:app_id => #app.id).where("last_run_date is not ?", nil).group("CAST(run_at AS DATE)").order("date desc")
#messages << MessageHistory.select("SUM(devices_count) as count ,CAST(run_at AS DATE) AS date").where(:app_id => #app.id).where("last_run_date is not ?", nil).group("CAST(run_at AS DATE)").order("date desc")
#messages = #messages.flatten.paginate(:page => params[:page] || 1, :per_page => 100)
It sounds like what you want is to UNION the two tables, then paginate the results.
See ActiveRecord Query Union for some examples, and look at the active_record_union gem (which makes it easier to do UNIONs with ActiveRecord).
It will take some experimentation to figure out how to apply the where clause filters and sums/groups properly!

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)

How can I use .all for last 2 days in Rails3?

I have a model called submission and currently I am displaying all the records in the database in the index page. In the submissions controller I have :
#submissions = Submission.all
However, now I only want the record for the past two days or the name field equals to some string, I tried this but it still shows all the records for me:
#submissions = Submission.all(:conditions => ["updated_at >= ? OR name = ?", 2.days.ago.to_date, "me"])
where updated_at and name are two fields in the submissions table.
Any idea where is wrong?
EDIT:
In my submission model:
attr_accessible :name, :updated_at
In Arel (Rails 3), your conditions should be in a where method, with (optionally) at the end, like so
Submission.where("updated_at >= ? OR name = ?", 2.days.ago.to_date, "me").all

Rails :order by date in Postgres returning incorrect order

I have a model called Story that I'm trying to order by the created_at date. Since I've hosted my app on Heroku, which uses Postgresql, I have the following in my controller:
#stories = Story.find( :all, :order => "DATE(created_at) DESC" , :limit => 11)
I would expect this to give the first 11 of my stories, ordered by the creation date, with the newest story first.
Unfortunately, this doesn't work. Most of the stories return ordered correctly, but the first two are flipped. That is, the latest story appears second in the list.
Why would this be? I have a sneaky suspicion that my results aren't ordered at all or are being ordered on the wrong column (maybe id?) and that until now it just happened to be ordered like I expected when displayed on my index page. How can I get it to order as I expect it to?
In case anyone cares, the index view is simply displaying the stories, in order. That is (HAML):
- #stories.each do |story|
= render :partial => "event", :locals => { :event => story }
EDIT
I am suspicious that the created_at is a datetime column and the DATE(...) function disregards the time portion. So it returns the elements created on the same date in a random order. Since the first two stories were created on the same day, but several hours apart, which would explain why they seem to be 'reversed'. If this is the case, what would be the correct syntax to order by both date and time?
I believe you want:
#stories = Story.find(:all, :order => "created_at DESC" , :limit => 11)
Update for Rails 3+:
#stories = Story.order(created_at: :desc).limit(11)
If you are using Rails 3, I would also encourage you to use the cool new query syntax which would be:
#stories = Story.order('created_at DESC').limit(11)
See Active Record Query Interface for more information.

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