Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Rails:保存父记录后立即自动创建关联记录_Mysql_Ruby On Rails_Associations_Has Many Through - Fatal编程技术网

Mysql Rails:保存父记录后立即自动创建关联记录

Mysql Rails:保存父记录后立即自动创建关联记录,mysql,ruby-on-rails,associations,has-many-through,Mysql,Ruby On Rails,Associations,Has Many Through,我正在尝试在保存父记录后立即在子表中自动创建记录,但我遇到了问题,需要帮助才能做到这一点 所以我的Orgs表层次结构类似于Org->Brand->Restaurant (例如Americana(Org)->肯德基(品牌)->旧金山(餐厅)) 一个品牌有很多菜单,菜单属于一个品牌。现在我想从品牌菜单中逐级列出每家餐厅的菜单,因为我想由餐厅管理价格。为了做到这一点,我创建了一个“本地菜单”表,其中包含餐厅id和菜单id,这样我就不必复制一些数据,本地菜单中的更改也不会影响到其父菜单 问题是如何在创建

我正在尝试在保存父记录后立即在子表中自动创建记录,但我遇到了问题,需要帮助才能做到这一点

所以我的Orgs表层次结构类似于Org->Brand->Restaurant (例如Americana(Org)->肯德基(品牌)->旧金山(餐厅))

一个品牌有很多菜单,菜单属于一个品牌。现在我想从品牌菜单中逐级列出每家餐厅的菜单,因为我想由餐厅管理价格。为了做到这一点,我创建了一个“本地菜单”表,其中包含餐厅id和菜单id,这样我就不必复制一些数据,本地菜单中的更改也不会影响到其父菜单

问题是如何在创建父菜单后立即在“本地菜单”中自动创建记录。更具体地说,当我创建菜单时,需要为该品牌下的所有餐厅自动创建相同的菜单。感谢您的支持

型号:

class LocalMenu < ActiveRecord::Base
  belongs_to :restaurant
  belongs_to :menu
end

class Menu < ActiveRecord::Base
    has_many :local_menus
    belongs_to :brand
end

class Restaurant < ActiveRecord::Base
    has_many :menus, through: :local_menus
end

一种方法是使用
:after_create
回调为该品牌的所有餐厅创建本地菜单

class Menu < ActiveRecord::Base

  after_create: :build_local_menus_for_brand

  def build_local_menus_for_brand
    brand.restaurants.each do |restaurant|
      self.local_menus.create!(restaurant_id: restaurant.id)
    end
  end
end
class菜单
一种方法是使用
:after\u create
回调为该品牌的所有餐厅创建本地菜单

class Menu < ActiveRecord::Base

  after_create: :build_local_menus_for_brand

  def build_local_menus_for_brand
    brand.restaurants.each do |restaurant|
      self.local_menus.create!(restaurant_id: restaurant.id)
    end
  end
end
class菜单
它应该是
self.local\u menu.create!(restaurant\u id:restaurant.id)
,我想这就足够了。它应该是
self.local\u menumes.create!(restaurant\u id:restaurant.id)
,我想这就足够了。根据下面的答案,您还需要添加一个您在
restaurant
中缺少的关联,即
所属:brand
根据下面的答案,您还需要添加一个您在
restaurant
中缺少的关联,即。,
属于:品牌