我卡住了(。我有两个与habtm关系的模特。
create_table "daily_menus", force: :cascade do |t|
t.string "day"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "date"
end
add_index "daily_menus", ["day"], name: "index_daily_menus_on_day", unique: true, using: :btree
create_table "daily_menus_dishes", id: false, force: :cascade do |t|
t.integer "daily_menu_id"
t.integer "dish_id"
end
add_index "daily_menus_dishes", ["daily_menu_id", "dish_id"], name: "index_daily_menus_dishes_on_daily_menu_id_and_dish_id", using: :btree
create_table "dish_types", force: :cascade do |t|
t.integer "meal"
end
create_table "dishes", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "dish_type_id"
end
add_index "dishes", ["dish_type_id", "name"], name: "index_dishes_on_dish_type_id_and_name", unique: true, using: :btree
还有一张与菜肴有关的dish_type表:菜肴。我需要的是一个范围,其中包括指定类型的所有菜肴,除了那些已经在菜单中的菜肴。我第二天正在与这个问题作斗争。需要一些帮助。这是我最后一次失败的考试
#scope :menu_available, -> (type_id, daily_menu_id){ where('dish_type_id = ?', type_id) & where(joins(:daily_menus).where.not('daily_menu_id = ?', daily_menu_id)) }
#scope :menu_available, lambda { |type_id, daily_menu_id| joins(:daily_menus).where('dishes.dish_type_id = ? AND daily_menus.id != ?', type_id, daily_menu_id) }
#scope :menu_available, lambda { |daily_menu_id| joins(:daily_menus).where('daily_menus.id is NULL AND daily_menus.id != ?', daily_menu_id) }
scope :menu_available, -> { joins(:daily_menus).where(daily_menus: { id: 17 }) }
scope :menu_available, -> { where("dish_type_id = ?", 14).joins(:daily_menus).where("daily_menu_id != ?", 17)}
我取得了一点成功,现在它找到了菜单中未包含的所有菜肴
scope :without_menu, -> { joins('LEFT JOIN daily_menus_dishes ON dishes.id = daily_menus_dishes.dish_id').where('daily_menus_dishes.daily_menu_id is NULL')}
取得了一些更大的成功!!
scope :without_menu, -> { joins('LEFT JOIN daily_menus_dishes ON dishes.id = daily_menus_dishes.dish_id').where('daily_menus_dishes.daily_menu_id is NULL OR daily_menus_dishes.daily_menu_id != ?', 14) }
答案 0 :(得分:0)
我在这里得到的,可能是重构的吗?
scope :without_menu, -> { joins('LEFT JOIN daily_menus_dishes ON dishes.id = daily_menus_dishes.dish_id').where('daily_menus_dishes.daily_menu_id is NULL OR daily_menus_dishes.daily_menu_id != ?', 14).where(dish_type: 14).order('name ASC') }