收货时:
{
parent:{
children_attributes:[
{child1}, {child2}
]
}
}
child1
实例即将创建,我没有设置parent_id
。我想这是在节省时间中设置的。
我该如何处理这个问题,比如:
class Child < ActiveRecord::Base
belongs_to :parent
before_save :do_something
def do_something
# access parent here
# I can't, since parent_id is nil yet
end
end
更新更清楚
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
end
更新 2
我从相关问题中尝试了这个:
class Parent < ActiveRecord::Base
has_many :children, inverse_of: :parent
end
但同样的问题。
根据评论更新3
我试过这个
class Parent
before_save :save_children
attr_accessor :children_attributes
def save_children
children_attributes.all? do |k, attrs|
# tried different things here, this one is the one I expected to work the most
child = Child.new attrs.merge(parent_id: id)
child.save
end
end
我将 parent_id 添加到子 attr_accessible 调用中。
我错过了什么?