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

发布于 2024-08-25 09:17:45 字数 854 浏览 6 评论 0原文

在此视频(10秒)中,您可以看到嵌套属性仅在其父模型为改变了。

使用rails 3.0.0.beta 和完整项目位于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

In this video (10 sec) you can see that the nested attribute is only updated if it's parent model is changed.

Using rails 3.0.0.beta and the full project is on github.

Summary of models and form:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飞烟轻若梦 2024-09-01 09:17:45

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

它运行没有错误。

EDIT2: The same code works perfectly in Rails 2.3.5. It seems to be a bug in beta version.

EDIT: I wrote a test in my app to simulate this. Here's the result.

  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

It runs without errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文