2013-07-12 22 views
1

因此,我正在尝试使用find_by_created_at方法创建日期来查询microposts。首先,我发现,像这样在轨控制台微柱:如何使用Rails中的find_by_created_at从数据库中检索项目

1.9.3-p194 :027 > Micropost.first 

Micropost Load (2.7ms) SELECT "microposts".* FROM "microposts" ORDER BY microposts.created_at DESC LIMIT 1 => #<Micropost id: 409, content: "Apparently it does not like spaces either. Check t...", user_id: 1, created_at: "2013-07-11 22:51:44", updated_at: "2013-07-11 22:51:44", receiver: "self">

然后我复制并粘贴created_at输入(减去时间戳)到我find_by_created_at方法,像这样:

1.9.3-p194 :028 > Micropost.find_by_created_at("2013-07-11")

Micropost Load (0.8ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."created_at" = '2013-07-11 22:51:44' ORDER BY microposts.created_at DESC LIMIT 1 => nil

由于某种原因它返回零。我认为这个问题可能是因为我没有包括时间,但我也用时间戳来尝试它,它仍然回零。

我的计划是让用户按日期搜索和显示微博。也许是这样的:

Micopost.find_by_created_at(@search_date).all

但我正在逐渐挂断了电话只是想通过created_at找到。有人能指出我正确的方向吗? 感谢

回答

1

你可以尝试这样的事:

Micopost.where("DATE(created_at) = ?", "2013-07-11") # Mysql/sqlite database 

Micopost.where("created_at::date = ?", "2013-07-11") # PostgreSQL 
+1

如果MySQL是你的数据库 –

+0

是的,非常真实的。我已经添加了这个答案,以及PostgreSQL以防万一,谢谢。 – NicoSantangelo

+0

这工作,感谢您的帮助。 – Bw00d

0
Micopost.where(" created_at between ? AND ?", @search_date.beginning_of_day, @search_date.end_of_day) 

您还可以用户ryan bigg's by_star gem:

Micropost.by_day("2013-07-11") 
相关问题