하루에 작성된 의견을 쿼리해야합니다. 이 필드는 표준 타임 스탬프의 일부입니다 created_at
. 선택한 날짜는에서 시작됩니다 date_select
.
어떻게 사용 ActiveRecord
합니까?
나는 다음과 같은 것이 필요하다 :
"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"
답변
Rails 3에서는 현재 허용되는 답변이 더 이상 사용되지 않습니다. 대신이 작업을 수행해야합니다.
Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)
또는 순수한 문자열 조건 을 원하거나 사용해야하는 경우 다음을 수행 할 수 있습니다.
Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)
답변
개인적으로 더 읽기 쉽고 재사용 할 수있는 범위를 만들었습니다.
Comment.rb에서 범위를 정의 할 수 있습니다.
scope :created_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}
그런 다음 사이에 생성 된 쿼리 :
@comment.created_between(1.year.ago, Time.now)
도움이 되길 바랍니다.
답변
Rails 5.1은 새로운 날짜 도우미 메소드를 도입했습니다 all_day
. 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
Rails 5.1을 사용하는 경우 쿼리는 다음과 같습니다.
Comment.where(created_at: @selected_date.all_day)
답변
이 코드는 당신을 위해 작동해야합니다 :
Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})
자세한 내용은 시간 계산을 참조하십시오
참고 : 이 코드는 더 이상 사용되지 않습니다 . Rails 3.1 / 3.2를 사용하는 경우 답변의 코드를 사용하십시오.
답변
이 코드를 실행하여 확인 된 답변이 효과가 있는지 확인하고 날짜를 바꿔서 올바르게 사용해야했습니다. 이것은 효과가 있었다.
Day.where(:reference_date => 3.months.ago..Time.now).count
#=> 721
출력이 36이되어야한다고 생각한다면, 이것을 생각해보십시오.
답변
Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])
답변
2 대신 3 점을 사용하고 있습니다. 3 점은 처음에 열리고 끝에서 닫히는 범위를 제공하므로 후속 범위에 대해 2 개의 쿼리를 수행하면 동일한 행을 다시 가져올 수 없습니다 양자 모두.
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 []>
그리고 항상 스코프를 사용하는 것이 좋습니다!
