I stuck (.I have two models with habtm relationship.
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
And also a table of dish_type with relation to dishes has_many :dishes. What I need is a scope where all dishes with specified type would be included except those that are already in menu. Im fighting with this problem for the second day. Need some help. Here are my last failure attepts
#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)}
I have a small success, now it finds all dishes that are not included in menu
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')}
some bigger success!!
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) }