Rails 3.1没有从nested_form渲染fields_for

时间:2011-12-07 10:44:12

标签: ruby-on-rails ruby-on-rails-3.1 nested-forms simple-form nested-form-for

我有一个has_many :tasks的项目模型。我在rails 3.1中添加了一个嵌套资源,现在尝试使用nested_form gem来编辑项目时添加/删除任务。

我之前在另一个Rails3应用程序中使用了nested_form,它工作正常,但现在我的fields_for部分没有呈现任何内容。

这是我的代码:

#project.rb
class Project < ActiveRecord::Base

  attr_accessible :nr, :name, :client_id, :project_status_id, :hidden, :active, :description, :tasks_attributes


  has_many :tasks, :dependent => :destroy
  accepts_nested_attributes_for :tasks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true


end


#task.rb
class Task < ActiveRecord::Base

  belongs_to :project

end

#views/projects/_form.html.erb
<%= simple_nested_form_for @project do |form| %>

  <%= form.input :nr, :label => 'Nr' %>
  <%= form.input :name, :label => 'Name' %>
  <%= form.association :client, :collection => Client.all(:order => 'name'), :prompt => "Choose a Client" %>
  <%= form.input :description, :label => 'Description' %>
  <%= form.input :active, :label => 'Active' %>
  <%= form.input :hidden, :label => 'Hidden' %>
  <div class="task_fields">
    <%= form.fields_for :tasks do |task_form| %>
      <%= task_form.input :name %>
      <%= task_form.input :description  %>
      <%= task_form.input :deadline %>
      <%= task_form.link_to_remove "Remove this task" %>
      <p><%= form.link_to_add "Add a task", :tasks %></p>
     <% end %>
  </div>
  <div class="actions">
    <%= form.button :submit %>
  </div>
<% end %>

在我的路线中:

  resources :posts do 
    resources :comments
  end

但是当我在浏览器中访问该页面时

<div class="task_fields"></div>

呈现为空。没有fields_for和anysoever。加载了nested_form.js并将我的GEMFILE指向gem "nested_form", :git => 'https://github.com/fxposter/nested_form.git',因为我在某处需要这样做才能获得simple_form支持。我还尝试将simple_nested_form_for更改为仅nested_form_for,但没有效果。

任何高度赞赏的帮助

1 个答案:

答案 0 :(得分:15)

projects#new中,您必须初始化至少一项任务,否则您的fields_for部分将不会显示任何内容。

# projects_controller.rb
def new
  @project = Project.new
  @project.tasks.new
end

如果您需要多个任务:

n.times { @project.tasks.new } # replace n with the number of tasks needed