开发者

Rails 3.1 cocoon gem for nested forms

开发者 https://www.devze.com 2023-04-12 05:06 出处:网络
I\'m actually trying cocoon gem(by nathanvda) along with simple_form gem to dynam开发者_运维百科ically add and remove fields on a form .I don\'t understand why the nested form doen\'t show up on my fo

I'm actually trying cocoon gem(by nathanvda) along with simple_form gem to dynam开发者_运维百科ically 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 %> 


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.


Thanks for the head ups nathanvda.I finally find a gem to handle nested fields, Here is the link: https://github.com/lailsonbm/awesome_nested_fields.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号