Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 not rendering the fields_for from nested_form

I have a project model that has_many :tasks. I added a nested resource in rails 3.1 and try now with the nested_form gem to be able to add/delete tasks when editing a project.

I used nested_form before in another Rails3 application and it worked fine, but now my fields_for part does not render anything.

Here is my code:

#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 %>

and in my routes:

  resources :posts do 
    resources :comments
  end

but when I visit the page in my browser the

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

is rendered empty. no fields_for and whatsoever. the nested_form.js is loaded and I point in my GEMFILE to gem "nested_form", :git => 'https://github.com/fxposter/nested_form.git', as I read somewhere I need to do this in order to get simple_form support. I tried also to change simple_nested_form_for to only nested_form_for with no effect.

Any help higly appreciated

like image 688
tmaximini Avatar asked Dec 07 '11 10:12

tmaximini


1 Answers

In projects#new, you have to initialize at least one task otherwise your fields_for part won't display anything.

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

If you want more than one task:

n.times { @project.tasks.new } # replace n with the number of tasks needed  
like image 91
Damien Avatar answered Nov 04 '22 20:11

Damien