26

Finally moved to Rails 3 for a new project and already running into a rookie problem.

Trying to do a simple nested form.

2 models: list and tasks

List model

class List < ActiveRecord::Base
  has_many :tasks, :dependent=>:destroy
  accepts_nested_attributes_for :tasks, :reject_if => lambda { |a| a[:name].blank? }
end

Task Model

class Task < ActiveRecord::Base
  belongs_to :list

end

List Controller

def new
   @list = List.new
   3.times{ @list.tasks.build }
end

lists/new.html.erb

<% form_for :list, :url=>{:action=>"create"} do |f| %>
    <%= f.text_field :name, :class=>'big' %>
    <%= f.label :name, "ex: Today's Todos, Christmas List" %>

    <% f.fields_for :tasks do |builder| %>
        <p>
            <%= builder.label :name, "Task" %>
            <%= builder.text_field :name %>
            <%= builder.check_box :_destroy %>
        </p>
    <% end %>

    <p><%= submit_tag "Create List", :id => "submit", :name => "submit", :class => "form_submit", :disabled => false, :disable_with => "Please wait..." %></p>

<% end -%>

Using debug @list I can see the 3 tasks I created in my controller, but it fields_for won't render.

Any ideas?

Ryan
  • 379
  • 1
  • 5
  • 11

2 Answers2

81

In rails 3, you should use <%= instead of <% for form_for and fields_for . See if that helps.

bowsersenior
  • 12,000
  • 2
  • 44
  • 51
  • That fixed that problem ... now only 1 of 3 task text_fields are showing up ... any ideas? – Ryan Dec 11 '10 at 03:03
  • nm ... got it. I wasn't using the instance variable I created in the form_for – Ryan Dec 11 '10 at 03:06
  • 2
    Cool, glad you got the problems solved. You may want to have a look at https://github.com/plataformatec/simple_form or https://github.com/justinfrench/formtastic in the future to make rails forms easier to deal with. – bowsersenior Dec 11 '10 at 03:08
  • OK, try this on rails 2.3.5: `return content_tag('li', render_single_menu_node(node, content_tag(:span, caption), url, selected), {}, false)` – bowsersenior Dec 11 '10 at 07:18
  • 1
    I love you! Three days of research, and no solutions found. Except this! – marzapower Nov 11 '11 at 23:23
  • 1
    @marzapower I'm glad this helped you! – bowsersenior Nov 14 '11 at 23:42
  • Why do you need to use – Huey Mar 01 '12 at 06:29
  • @Huey the helpers output viewable content, so it makes sense that your use ` – bowsersenior Mar 01 '12 at 19:59
  • Ugh, so much of the Internet still has out of date information on fields_for, and it's such an easy one to miss reading the API docs. Horrible little issue! Thanks for the answer so much. – Dave Mar 02 '12 at 19:19
  • That saved me from pulling a few hairs out of my already bald head! – DGM May 23 '12 at 02:21
0

In your list controller in action new you have to add

 def new
   @list = List.new
   3.times{ 
   @tasks = @list.tasks.build
   }
end
Rob
  • 4,809
  • 12
  • 48
  • 49