我正在尝试在更新父属性后立即更新关联表的属性。因此菜单表是主表,并且每当更新主表时,需要更新子表(例如,active_status)中的关联属性。为了做到这一点,我在菜单模型中添加了'after_update'回调。但是,我得到的是下面的错误。我在这做错了什么?
错误
MenusController中的NoMethodError #update undefined方法`menu_states' 为零:NilClass
摘录来源(第54行):52 53 54 55 56 57
def update_menu_states_for_menu @ menu.menu_states do | menu_state | self.menu_states.update_attributes(menu_id:menu_state.id,price:menu_state.price,active_status:menu_state.active_status) 结束
menu.rb
class Menu < ActiveRecord::Base
after_update :update_menu_states_for_menu
def update_menu_states_for_menu
menu.menu_states do |menu_state|
self.menu_states.update_attributes!(menu_id: menu_state.id, price: menu_state.price, active_status: menu_state.active_status)
end
end
模型
class MenuState < ActiveRecord::Base
belongs_to :menu
end
class Menu < ActiveRecord::Base
has_many :menu_states
end
表
local_menus
t.integer "restaurant_id", limit: 4
t.integer "menu_id", limit: 4
t.boolean "active_status", limit: 1
t.boolean "instock_status", limit: 1
t.integer "price", limit: 4
t.integer "selling_price", limit:4
menus
t.integer "restaurant_id", limit: 4
t.string "name", limit: 255
t.integer "price", limit: 4
t.integer "brand_id", limit: 4
t.integer "category_id", limit: 4
t.text "description", limit: 65535
t.boolean "active_status", limit: 1
t.date "start_date"
t.date "end_date"
答案 0 :(得分:1)
它将是self.menu_states
而不是menu.menu_states
def update_menu_states_for_menu
self.menu_states do |menu_state| #
menu_state.update_attributes!(menu_id: menu_state.id, price: menu_state.price, active_status: menu_state.active_status)
end
end
答案 1 :(得分:0)
您需要使用booktabs
像这样定义Menu
模型:
class Menu < ActiveRecord::Base
has_many :menu_states, autosave: true
end