Rails 3: How to find rows in a table that was created today?

I would like to use an instruction like ...

current_user.workouts.find_by_created_at(Time.now.day)

but this does not work, I suppose, because times do not coincide. I will continue to read documents, but I thought I would post this question to ask for help while I read.

Thanks!

UPDATE Using the new Rails 3 support for AREL and named areas, I reorganized the request to ...

Model

  class Workout < ActiveRecord::Base scope :from_today, where(" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day) . . . end 

controller

 def create workouts = current_user.workouts.from_today . . . end 
+4
source share
3 answers
 current_user.workouts.find(:all, :conditions => [" YEAR(created_at) = ? AND MONTH(created_at) = ? AND DAY(created_at) = ?", Time.zone.now.year, Time.zone.now.month, Time.zone.now.day]) 

or

 current_user.workouts.find(:all, :conditions => [" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day]) 

not sure more optimized

+3
source

If you are using MySQL, you can do the following:

Rails 3:

 current_user.workouts.where('DATE(created_at) = ?', Date.today) 

Rails 2:

 current_user.workouts.find(:all, :conditions => ['DATE(created_at) = ?', Date.today]) 
+5
source

I wrote a gem for this kind of operation called by_star . With it, you can do this to create all the entries created today:

 current_user.workouts.today 

There are also many other useful methods. Let him go.

+3
source

Source: https://habr.com/ru/post/1346830/


All Articles