我碰到了这个post,与我想做的事情类似。
Person.left_outer_joins(:contacts).where( contacts: { id: nil } )
唯一的区别是我需要更深一层。我的设置是Restaurant
,其中有许多Dishes
,而这些菜肴又与部分具有HMT关联。我只想找到没有相关部分的菜肴。我尝试做类似的事情:
Restaurant.left_outer_joins(:dishes).where(dishes: { section_ids: nil })
但是出现此错误:
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column dishes.section_ids does not exist)
LINE 1: ...ishes"."restaurant_id" = "restaurants"."id" WHERE "dishes"."...
^
: SELECT "restaurants".* FROM "restaurants" LEFT OUTER JOIN "dishes" ON "dishes"."restaurant_id" = "restaurants"."id" WHERE "dishes"."section_ids" IS NULL LIMIT $1
class Restaurant < ApplicationRecord
has_many :dishes, dependent: :destroy
end
class Dish < ApplicationRecord
has_many :dish_sections, dependent: :destroy
has_many :sections, through: :dish_sections
belongs_to :restaurant
end
class Section < ApplicationRecord
has_many :dish_sections, dependent: :destroy
has_many :dishes, through: :dish_sections
end
class DishSection < ApplicationRecord
belongs_to :dish
belongs_to :section
end