问题是当 aRestaurant
没有任何MenuItems
匹配条件时,ActiveRecord 说它找不到Restaurant
. 以下是相关代码:
class Restaurant < ActiveRecord::Base
has_many :menu_items, dependent: :destroy
has_many :meals, through: :menu_items
def self.with_meals_of_the_week
includes({menu_items: :meal}).where(:'menu_items.date' => Time.now.beginning_of_week..Time.now.end_of_week)
end
end
并且生成的sql代码:
Restaurant Load (0.0ms)←[0m ←[1mSELECT DISTINCT "restaurants".id FROM "restaurants"
LEFT OUTER JOIN "menu_items" ON "menu_items"."restaurant_id" = "restaurants"."id"
LEFT OUTER JOIN "meals" ON "meals"."id" = "menu_items"."meal_id" WHERE
"restaurants"."id" = ? AND ("menu_items"."date" BETWEEN '2012-10-14 23:00:00.000000'
AND '2012-10-21 22:59:59.999999') LIMIT 1←[0m [["id", "1"]]
但是,根据Rails Guides的这一部分,这不应该发生:
Post.includes(:comments).where("comments.visible", true)
如果在这种包含查询的情况下,任何帖子都没有评论,那么仍然会加载所有帖子。