如何获得记录创建今天的轨道活动记录?

当我想要得到今天创建的所有记录时,我应该如何编写 If判断语句?

88925 次浏览

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
Post.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)

PS: This answer has been modified as answer by Harish Shetty was better than mine. As my answer is accepted one. I have updated this answer for community support

我知道这个问题有一个公认的答案。当表大小增长时,接受的答案中建议的解决方案可能会导致性能问题。

Typically, if you perform lookups based on created_at column, add an index on the table in your migration file.

add_index :posts, :created_at

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

Rails 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])

——

向模型中添加一个 name _ scope

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


Post.today #returns posts today

Mohit Jain 的答案改编自 Rails3

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

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.3中,使用 mysql 获取今天创建的记录,请使用以下内容。

@ usertarget = Goal.where (“ userid = : userid and Date (create _ at) = : Date”,{ userid: params [ : id ] ,Date: Date.today })

这里我使用多个条件,如果你想你可以编辑它的单一条件。

Where (create _ at: Time.zone.now.start _ of _ day. . Time.zone.now.end _ of _ day)

这个“名称”使用 table_name对属性进行“命名”。

由于某些原因,本文中的其他解决方案和 StackOverflow 上的其他解决方案都不适合我(使用 Rails 4.2.4和 Ruby 2.2.3 p173)。这是我唯一可以用 Postgres 数据库查询的内容:

Post.where("created_at >= TIMESTAMP 'now'")

查询从今天创建的记录

Use scope with arel

class Post < ActiveRecord::Base
scope :create_from_today, -> {
where(arel_table[:created_at].gteq(Time.zone.now.beginning_of_day))
}
end

Then we can use it

today_posts = Post.created_from_today

Rails 5.1有一个 all_day助手,在这里很有用。

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

or

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