结合范围的fields_for和一个额外的表单渲染

时间:2013-05-04 09:02:37

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

让我们说我正在编写一个简单的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而没有任何范围时,来自表单帮助程序的代码才能完美。当我添加它们时,不会显示其他表单构建。

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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

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