如果我想获取所有今天创建的记录,应该如何编写条件语句?
如果我想获取所有今天创建的记录,应该如何编写条件语句?
Post.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)
PS:这个答案已经被修改,因为Harish Shetty的答案比我的更好。由于我的答案被接受了,我已经更新了这个答案以得到社区的支持。
我知道这个问题有一个被接受的答案。然而,被接受的答案中提到的解决方案可能会在表格大小增长时导致性能问题。
通常情况下,如果你基于 created_at
列进行查询,需要在迁移文件中为表格添加索引。
add_index :posts, :created_at
Post.where("created_at >= ?", Time.zone.now.beginning_of_day)
Post.where(:created_at => (date.beginning_of_day..date.end_of_day))
在您的模型中添加一个静态方法
class Post < ActiveRecord::Base
def self.today
where("created_at >= ?", Time.zone.now.beginning_of_day)
end
end
Post.today #returns posts today
Rails 2
Post.all(:conditions => ["created_at >= ?", Time.zone.now.beginning_of_day])
为您的模型添加一个命名作用域
class Post < ActiveRecord::Base
named_scope :today, lambda {
{
:conditions => ["created_at >= ?", Time.zone.now.beginning_of_day]
}
}
end
Post.today #returns posts today
scope
示例仅适用于 Rails 3,因为它似乎在 Rails 2 标题下。在 Rails 2 中,您需要使用 named_scope
而不是 scope
。此外,在 Rails 3 中,您可以等效地使用类方法def self.today where("created_at >= ?", Time.now.beginning_of_day) end
在这种情况下,这可能比使用作用域更清晰,因为它允许您放弃 lambda。 - evanrmurphyRails 5.1有一个all_day
助手函数,在这里非常有用。
Post.where(created_at: Date.today.all_day)
或者Post.where(created_at: Date.parse("YYYY-MM-DD").all_day)
MySQL:
Model.all :condition => ["DATE(created_at) = ?", Date.today] # rails 2
Model.where("DATE(created_at) = ?", Date.today) # rails 3
PostgreSQL:
Model.all :condition => ["created_at::date = ?", Date.today] # rails 2
Model.where("created_at::date = ?", Date.today) # rails 3
为 Rails3 改编的 Mohit Jain 的答案
Model.where "DATE(created_at) = DATE(?)", Time.now
Post.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)
这将在table_name
中添加“namescopes”属性。
model.rb
scope :posted_today, -> { posted_between_period(Time.now.midnight, Time.now.end_of_day) }
posts_controller.rb
Post.posted_today
由于某种原因,此帖子中的其他解决方案以及StackOverflow上的其他解决方案都无法在我的Postgres数据库中使用(使用Rails 4.2.4和Ruby 2.2.3p173)。这是我唯一能够使查询工作的查询:
Post.where("created_at >= TIMESTAMP 'now'")
查询从今天起创建的记录
使用arel作用域
class Post < ActiveRecord::Base
scope :create_from_today, -> {
where(arel_table[:created_at].gteq(Time.zone.now.beginning_of_day))
}
end
然后我们可以使用它
today_posts = Post.created_from_today
where('created_at >= now()')
只会找到创建时间在未来的项目。 - Paul Danelli.lteq(Time.zone.now.end_of_day))
。 - Paul Danelli
Post.where(created_at: Time.current.all_day)
更加简化。 - Eyeslandic