Rails ActiveRecord fecha entre


Necesito consultar los comentarios realizados en un día. El campo es parte de las marcas de tiempo estándar, es created_at. La fecha seleccionada proviene de un date_select. ¿Cómo puedo usar ActiveRecord para hacer eso?

Necesito algo como:

"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"
Author: user2262149, 2010-03-04

11 answers

Solo una nota que la respuesta actualmente aceptada está obsoleta en Rails 3. Usted debe hacer esto en su lugar:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

O, si quieres o tienes que usar condiciones de cadena pura , puedes hacer:

Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)
 337
Author: ndbroadbent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-16 18:26:45

Yo personalmente crearía un alcance para hacerlo más legible y reutilizable:

En tu Comentario.rb, puede definir un ámbito:

scope :created_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}

Luego a la consulta creada entre:

@comment.created_between(1.year.ago, Time.now)

Espero que ayude.

 38
Author: Marshall Shen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-23 16:32:26

Este código debería funcionar para usted:

Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})

Para obtener más información, eche un vistazo a Cálculos de tiempo

Nota: Este código es obsoleto. Utilice el código de la respuesta si está utilizando Rails 3.1/3.2

 20
Author: Irukandji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-15 23:37:11

Rails 5.1 introdujo un nuevo método auxiliar de fecha all_day, ver: https://github.com/rails/rails/pull/24930

>> Date.today.all_day
=> Wed, 26 Jul 2017 00:00:00 UTC +00:00..Wed, 26 Jul 2017 23:59:59 UTC +00:00

Si está utilizando Rails 5.1, la consulta se vería así:

Comment.where(created_at: @selected_date.all_day)
 13
Author: Bismark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 18:31:09

Ejecuté este código para ver si la respuesta marcada funcionaba, y tuve que intentar intercambiar las fechas para hacerlo bien. Esto funcionó--

Day.where(:reference_date => 3.months.ago..Time.now).count
#=> 721

Si usted está pensando que la salida debería haber sido 36, considere esto, Señor, ¿cuántos días es 3 días a 3 personas?

 8
Author: boulder_ruby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-05 01:45:12
Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])
 6
Author: kaushal sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-24 06:01:52

He estado usando los 3 puntos, en lugar de 2. Tres puntos le da un rango que está abierto al principio y cerrado al final, por lo que si realiza 2 consultas para rangos posteriores, no puede obtener la misma fila en ambos.

2.2.2 :003 > Comment.where(updated_at: 2.days.ago.beginning_of_day..1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" BETWEEN '2015-07-12 00:00:00.000000' AND '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 
2.2.2 :004 > Comment.where(updated_at: 2.days.ago.beginning_of_day...1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" >= '2015-07-12 00:00:00.000000' AND "comments"."updated_at" < '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 

Y, sí, siempre es bueno usar un visor!

 5
Author: nroose,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-28 10:26:53

Si solo quieres conseguir un día sería más fácil de esta manera:

Comment.all(:conditions => ["date(created_at) = ?", some_date])
 4
Author: klew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-04 18:54:37

Hay varias maneras. Puedes usar este método:

start = @selected_date.beginning_of_day
end = @selected_date.end_of_day
@comments = Comment.where("DATE(created_at) BETWEEN ? AND ?", start, end)

O esto:

@comments = Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)
 4
Author: ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 12:46:38

Creo que debería haber un comportamiento de active record por defecto en esto. Consultar fechas es difícil, especialmente cuando hay zonas horarias involucradas.

De todos modos, yo uso:

  scope :between, ->(start_date=nil, end_date=nil) {
    if start_date && end_date
      where("#{self.table_name}.created_at BETWEEN :start AND :end", start: start_date.beginning_of_day, end: end_date.end_of_day)
    elsif start_date
      where("#{self.table_name}.created_at >= ?", start_date.beginning_of_day)
    elsif end_date
      where("#{self.table_name}.created_at <= ?", end_date.end_of_day)
    else
      all
    end
  }
 4
Author: Augustin Riedinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-17 15:58:55

Puede usar la siguiente gema para encontrar los registros entre fechas,

Esta gema bastante fácil de usar y más clara Por star estoy usando esta gema y la API más clara y la documentación también bien explicada.

Post.between_times(Time.zone.now - 3.hours,  # all posts in last 3 hours
                  Time.zone.now)

Aquí usted podría pasar nuestro campo también Post.by_month("January", field: :updated_at)

Por favor vea la documentación y pruébela.

 1
Author: Jenorish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-05 12:57:18