我应该如何编写条件语句,以便何时要获得今天创建的所有记录?

有帮助吗?

解决方案

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

现在,今天创建的查找记录:

铁轨3/4

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

铁轨2

Post.all(:conditions => ["created_at >= ?", Time.zone.now.beginning_of_day])

--------- 或者 -------------

向您的模型添加nuper_scope

class Post < ActiveRecord::Base    
  named_scope :today, lambda { 
    {
      :conditions => ["created_at >= ?", Time.zone.now.beginning_of_day]
    }
  }
end

Post.today #returns posts today

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

Mohit Jain的答案适用于Rails3

Model.where "DATE(created_at) = DATE(?)", Time.now

Rails 5.1有一个 all_day 在这里很有用的帮手。

Post.where(created_at: Date.today.all_day)

或者

Post.where(created_at: Date.parse("YYYY-MM-DD").all_day)

Post.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)

此“名称”属性 table_name.

Model.RB

scope :posted_today, -> { posted_between_period(Time.now.midnight, Time.now.end_of_day) }

POST_CONTROLLER.RB

Post.posted_today

由于某种原因,这篇文章中的其他解决方案均未对我有用(使用Rails 4.2.4和Ruby 2.2.3p173)。这是我可以使用Postgres数据库的唯一查询:

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

在Rails 4.2.3中,使用MySQL使用以下内容,以获取今天创建的记录。

@usergoals = goal.Where(“ userId =:userId and date(created_at)=:date”,{userId:params [:id],date:date.today}))

在这里,如果您愿意,我可以使用多个条件,可以为单一条件进行编辑。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top