接收时:
{
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 调用中。
我错过了什么?
最佳答案
对我来说,这个问题的原因是验证父类在子类中的存在。
我基本上从 Child 对象中删除了这一行,它起作用了。
validates :parent, presence: true
然而,根据我的发现,解决此问题的正确方法是使用 inverse_of
参数。如果您将此添加到父级的 has_many
和子级的 belongs_to
,您就可以开始了。
在父级中:
has_many :child, inverse_of: :parent
在 child 身上:
belongs_to :parent, inverse_of: :child
关于ruby-on-rails - 使用 accepts_nested_attributes_for 时获取父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956230/