【问题标题】:Nested forms and automatic creation of parent, children嵌套表单和自动创建父、子
【发布时间】:2010-02-22 06:24:10
【问题描述】:

我想知道是否可以使用 Rails 嵌套表单创建新的父级,多个关系中的子级。

Rails 文档清楚地表明这是一对一的关系。不确定它是否相同有很多关系。

例如:

如果

params = { 
  :employee => { 
    :name => "Tester", 
    :account_attributes => {:login => 'tester'}
  }
} 

以一对一的关系运作。所以 Employee.new(params) 工作正常。新员工,帐户已创建。

假设我有

params = { 
  :employee => { 
    :name => "Tester", 
    :account_attributes => {
      "0" => {:login => 'tester'}, 
      "1" => {:login => 'tester2'}
    }
  }
} 

Employee.new(params) 不起作用。它在子验证上失败,说父级不能为空。

感谢任何帮助。谢谢

卡伦

【问题讨论】:

    标签: ruby-on-rails forms nested


    【解决方案1】:

    accepts_nested_attributes_for 附带的 child_attributes= writer 在涉及一对多关系时需要一个数组。

    这将为新员工创建两个帐户

    params = { 
      :employee => { 
        :name => "Tester", 
        :account_attributes => [
         {:login => 'tester'}, 
         {:login => 'tester2'}
        ]
      }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2018-07-14
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多