我有表项,并且该表与表item_views相关联,这是结构:
create_table "item_views", :force => true do |t|
t.integer "item_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
当我在数据库上运行这个 AR 查询时:
current_user.items.joins(:item_views).where("item_views.created_at > ? AND item_views.created_at < ?", date_from, date_to+1.day).count
然后生成以下 SQL 查询:
SELECT COUNT(*) FROM "items" INNER JOIN "item_views" ON "item_views"."item_id" = "items"."id" WHERE "items"."user_id" = 1 AND (item_views.created_at > '2013-09-10' AND item_views.created_at < '2013-09-20');
以下是item_views表中的数据:
select * from item_views;
1|1|2013-09-10 09:52:11.703811|2013-09-10 09:52:11.703811
2|1|2013-09-13 22:55:56.574696|2013-09-13 22:55:56.574696
3|1|2013-09-15 13:14:19.221074|2013-09-15 13:14:19.221074
4|2|2013-09-16 13:05:39.972383|2013-09-16 13:05:39.972383
5|3|2013-09-16 13:11:25.466117|2013-09-16 13:11:25.466117
6|1|2013-09-16 19:12:44.846686|2013-09-16 19:12:44.846686
(id、item_id、created_at、updated_at)
查询应该返回值3,但它返回的不是5 - 看起来在查询中忽略了条件"items"."user_id" = 1
。
这怎么可能,或者我错过了什么?
谢谢