Search code examples
ruby-on-railsformsrubygemsnestedcocoon-gem

Rails 3.1 cocoon gem for nested forms


I'm actually trying cocoon gem(by nathanvda) along with simple_form gem to dynamically add and remove fields on a form .I don't understand why the nested form doen't show up on my forms.Here's the code.(I'm newbie of course).Please can I have some help.

menu/_form.html.erb

<%= simple_form_for @menu do |f| %>

     <%= f.input :name %>
    <%= f.input :price %>

   <%= f.simple_fields_for :drinks do |drink| %>
       =render "drink_fields", :f => drink.links %> 
      <%= link_to_add_association "Add drink"%>
     <%end%> 

     <%= f.button :submit %> 
        <%end%>

menu/_drink_fields.html.erb

.nested-fields <%= f.input :name %> <%= link_to_remove_association "remove drink", f %>

these are the models

class Drinks < ActiveRecord::Base
    belongs_to :menu
end

class Menu < ActiveRecord::Base
    attr_accessible :drinks_attributes  

  has_many :drinks, :dependent => :destroy

  accepts_nested_attributes_for :drinks

end

in assets/javascripts/application.js

//= require cocoon

in layouts/application.html.erb

<%= javascript_include_tag :cocoon %> 

Solution

  • Your nested form is wrong, you are mixing haml and erb. If you have no personal preference yet, I would recommend using haml, I find it much easier and cleaner than erb.

    All that aside, your menu/_drink_fields.html.erb should look as follows:

    <div class='nested-fields'> 
      <%= f.input :name %> 
      <%= link_to_remove_association "remove drink", f %>
    </div>
    

    Also, inside your menu/_form.html.erb you should write the following:

    <%= f.simple_fields_for :drinks do |drink| %>
       <%= render "drink_fields", f: drink %> 
    <% end %>
    <%= link_to_add_association "Add drink", f, :drinks %>
    

    Hope this helps.