ruby-on-rails - 使用 accepts_nested_attributes_for 时获取父级

标签 ruby-on-rails associations

接收时:

{
   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/

相关文章:

ruby-on-rails - rails : populate an existing table via a migration

ruby-on-rails - 何时在 Rails 3 中使用虚拟属性或以散列形式传递数据

mysql - 需要有关 CakePHP 中的条件的一些帮助!

ruby - 这个多态关联有什么问题?

associations - 关于UML中的0对1和1对0的关联

java - 单向/双向 X 一/多 X 多/一关联关系

ruby-on-rails - 基于模型父属性的 rails 范围

Mysql2::Error 拒绝访问用户 'root' @'localhost'(使用密码:YES)

ruby-on-rails - 我如何判断是否使用了出售的 gem?

ruby-on-rails - Rails 4 通过方法查找或创建不起作用