0

假设我正在编写一个简单的 TODO 应用程序。用户可以向三个硬编码项目添加任务(使用fields_for方法),所以基本上,我的表单如下所示:

# task.first_project, task.second_project and task.third_project are a scopes for
# retrieving tasks, which belongs to chosen project.

= form_for setup_project(@project) do |f|
  h3 First project's tasks:
  = f.fields_for :tasks, f.object.tasks.first_project do |ff|
    = ff.text_field :title
    = ff.hidden_field :project_id, value: 1

  h3 Second project's tasks:
  = f.fields_for :tasks, f.object.tasks.second_project do |ff|
    = ff.text_field :title
    = ff.hidden_field :project_id, value: 2

  h3 Third project's tasks:
  = f.fields_for :tasks, f.object.tasks.third_project do |ff|
    = ff.text_field :title
    = ff.hidden_field :project_id, value: 3

我还有一个表单助手,用于在任务表单列表的末尾添加一个空任务表单:

  def setup_project(project)
    1.times { project.tasks.build }
    project
  end

这就是我的主要问题。仅当我在fields_for没有任何范围的情况下使用时,表单助手中的这段代码才能完美运行。当我添加它们时,不会显示额外的表单构建。

请注意:上面的例子只是我实际编程的一个非常简化的版本。请不要建议我重写我的应用程序以让更多动态项目添加功能或类似的东西。相信我,它真的需要以一种奇怪的方式工作:)

感谢您的任何帮助!

4

1 回答 1

0

我已经设法通过使用以下代码使其工作:

# task.first_project, task.second_project and task.third_project are a scopes for
# retrieving tasks, which belongs to chosen project.

= form_for @project do |f|
  h3 First project's tasks:
  = f.fields_for :tasks, setup_tasks(f.object.tasks.first_project) do |ff|
    = ff.text_field :title
    = ff.hidden_field :project_id, value: 1

  h3 Second project's tasks:
  = f.fields_for :tasks, setup_tasks(f.object.tasks.second_project) do |ff|
    = ff.text_field :title
    = ff.hidden_field :project_id, value: 2

  h3 Third project's tasks:
  = f.fields_for :tasks, setup_tasks(f.object.tasks.third_project) do |ff|
    = ff.text_field :title
    = ff.hidden_field :project_id, value: 3

form_helper:

def steup_tasks(tasks)
  tasks << tasks.build
end

但我不知道这是否是正确的解决方案。如果你知道更好,请分享它:)

于 2013-05-04T09:39:10.180 回答