Rails如何为子父关系创建递归的nested_form_for

时间:2015-06-25 08:42:09

标签: ruby-on-rails forms

模型是

class MenuItem < ActiveRecord::Base
  belongs_to :menu_item
  has_many :menu_items
  accepts_nested_attributes_for :menu_items
end

如何创建一个能够动态添加子项的表单以及子项的子项(如果需要)(最好使用nested_form_for)。换句话说,形式应该是这样的:

input
  child input
    child input (child of child)
    add/remove child (child of child of child)
  add/remove child (child)
add/remove input

点击添加/删除将根据孩子添加/删除一个,我该如何实现?

3 个答案:

答案 0 :(得分:0)

我认为你应该使用递归的部分视图。

产品:

class Item < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Item'
  has_many :children, :class_name => 'Item', :foreign_key => 'parent_id'
end

共享/ _items.html.erb:

<% items.each do |item| %>
  <div class="item" data-id="<%= item.id %>">
    <div class="content">
      <%= item.name %> <%= link_to 'Delete', item, :confirm => "Are you sure?", method: 'delete' %>
      <%= render partial: 'shared/items', locals: { items: item.children } if item.children %>
    </div>
  </div>
<% end %>

呈现物品:

first Delete
    first a Delete
    first b Delete 
second Delete
    second a Delete
    second b Delete
    second c Delete

答案 1 :(得分:0)

Cocoon应该可以正常处理您的用例。你需要做一些实验,因为深度嵌套是非常重要的。

答案 2 :(得分:0)

那么,你的想法是什么:

class MenuItem < ActiveRecord::Base
  belongs_to :parent, class_name: "MenuItem", foreign_key: "parent_id"
  has_many :childs, class_name: "MenuItem"
...
相关问题