代码之家  ›  专栏  ›  技术社区  ›  Cheng

当parent.children<<child时自动设置child.parent_id?

  •  0
  • Cheng  · 技术社区  · 15 年前

    如何使用ActiveRecord?我的代码:

    p = Product.create
    l = Label.create
    p.labels.add << l
    

    但我得到 l.parent == nil

      create_table "labels", :force => true do |t|
        t.integer  "product_id"
      end
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Hardryv    15 年前

    您的一些代码是合适的,因为您所要求的应该是自动工作的。

    class Parent < ActiveRecord::Base
      has_many :children
    end
    
    class Child < ActiveRecord::Base
      belongs_to :parent
    end
    

    如果您的代码与此不同,请发布一个更具体的问题。

    编辑: 你的 Product 模型中有任何验证吗?它们不会传递您上面的代码,您也不会检查返回值 create 所以你永远不会知道。

        2
  •  3
  •   Ryan Bigg Andrés Bonilla    15 年前

    你可以使用 acts_as_tree 为此: http://github.com/rails/acts_as_tree