ruby-on-rails – 在预先加载的关联上指定条件返回ActiveRecord :: RecordNotFound

问题是,当餐厅没有任何符合条件的MenuItem时,ActiveRecord说它找不到餐厅.这是相关的代码:

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)

如果在此包含查询的情况下,没有任何帖子的评论,则仍会加载所有帖子.

最佳答案 生成的SQL是您查询的正确翻译.但看看它,

只是在SQL级别(我缩短了一点):

SELECT *
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' AND '2012-10-21') 

左外联接完成了你期望他们做的工作:餐馆
与menu_items和饭菜相结合;如果没有menu_item
去餐厅,餐厅仍然保留在结果,与
所有缺少的部分(menu_items.id,menu_items.date,…)填入NULL

现在看看在哪里的第二部分:BETWEEN操作符要求,
menu_items.date不为null!还有这个
是您在没有用餐的情况下过滤掉所有餐厅的地方.

所以我们需要以使null-date ok的方式更改查询.

回到ruby,你可以写:

  def self.with_meals_of_the_week
    includes({menu_items: :meal})
       .where('menu_items.date is NULL or menu_items.date between ? and ?', 
            Time.now.beginning_of_week, 
            Time.now.end_of_week
        )
  end

结果SQL现在

.... WHERE (menu_items.date is NULL or menu_items.date between '2012-10-21' and '2012-10-28')

以及没有用餐的餐馆.

点赞