habtm范围的问题

时间:2016-10-14 19:23:28

标签: ruby-on-rails record

我与Dish和DailyMenu之间存在着一种关系。这是一个范围

  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)) }

它打算找到某种类型的菜肴,但目前尚未包含在菜单中。可悲的是,它无法正常工作。需要一些帮助 DishType模型

class DishType < ActiveRecord::Base
 include DishTypeSetter
 enum meal:[:main_course, :second_course, :drink]   
end

菜模型

class Dish < ActiveRecord::Base
  has_and_belongs_to_many :daily_menus
  has_many :orders
  has_many :users, through: :orders
  belongs_to :dish_type 

  scope :main_meals, -> { joins(:dish_type).where('meal = ?', 0) }
  scope :second_meals, -> { joins(:dish_type).where('meal = ?', 1) }
  scope :drinks, -> { joins(:dish_type).where('meal = ?', 2) }

  #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|
where(joins(:daily_menus).where('daily_menu_id != ? AND dish_type_id = ?', daily_menu_id, type_id))

}

  validates :dish_type, :name, presence: true
  validates :name, uniqueness: { scope: :dish_type_id }

end

菜单型号

class DailyMenu < ActiveRecord::Base
 has_and_belongs_to_many :dishes
 has_many :orders
 has_many :users, through: :orders
end

关于DishType模型 - 它只有has_many菜肴协会(我把它移到了一个问题)/但它没有has_many daily_menus /

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", force: :cascade do |t|
  t.integer "daily_menu_id"
  t.integer "dish_id"
end

create_table "dish_types", force: :cascade do |t|
  t.integer "meal"
end

create_table "dishes", force: :cascade do |t|
  t.string   "name"
  t.integer  "type"
  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

1 个答案:

答案 0 :(得分:2)

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)
}