嵌套表单子级仅在父级更改时才更新

时间:2010-03-19 13:10:47

标签: ruby-on-rails ruby-on-rails-3 nested-forms

In this video(10秒)您可以看到嵌套属性只有在更改了父模型时才会更新。

使用rails 3.0.0.beta和full project is on github

模型和表格摘要:

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
  has_many :assignments
  accepts_nested_attributes_for :assignments
end

class Assignment < ActiveRecord::Base
  belongs_to :task
end


form_for(@project) do |f|

  Project: f.text_field :name

  f.fields_for :tasks do |task_form|
    Task: task_form.text_field :name

    task_form.fields_for :assignments do |assignment_form|
      Assignment: assignment_form.text_field :name
    end
  end

  f.submit
end

1 个答案:

答案 0 :(得分:2)

EDIT2:相同的代码在Rails 2.3.5中完美运行。它似乎是测试版中的一个错误。

编辑:我在我的应用中编写了一个测试来模拟这个。这是结果。

  test "should update empresa" do
    addr = empresas(:ufba).address
    put_with users(:s_one), :update, :id => empresas(:ufba).to_param,
             :empresa => { :address_attributes => {:id => empresas(:ufba).address.to_param,
                                                   :city => "Feira de Santana"}}
    assert_not_nil assigns(:empresa)
    assert_not_same addr, assigns(:empresa).address, "Endereco nao foi atualizado"
    assert_redirected_to empresa_path(assigns(:empresa))
  end

它运行没有错误。