在Rails中以嵌套形式更新子对象

时间:2015-07-03 14:23:15

标签: ruby-on-rails

我的对象是一个部分。每个部分可以有其他部分。 部分响应#index,index返回其订单索引。如果某个部分没有兄弟部分,则为0。

我们假设我的数据结构是:

   a
 /   \
b     c

其中:

a.index = 0

b.index = 0

c.index = 1

如果我导航到/sections/a/manage-child-ordering,我希望能够编辑a小节的顺序。这是我视图中的代码:

<% if @section.children %>
    <%= form_for @section do |child| %>
      <%= f.fields_for :children, @section.children do |c| %>
        <%= c.text_field :index %>
      <% end %>
    <% end %>
<% end %>

<%= f.submit 'Save', class: 'btn-submit' %>

我得到的错误:

undefined method `errors' for #<Tag::ActiveRecord_Associations_CollectionProxy:0x007f23e60bdbd0>

我做错了什么?

2 个答案:

答案 0 :(得分:1)

在模型中添加它可以解决问题:

belongs_to :parent, class_name: 'Section'
has_many :children, class_name: 'Section', foreign_key: :parent_id

accepts_nested_attributes_for :children

答案 1 :(得分:0)

form_for不应该采用集合,它应该只采用负责实现表单操作的单个模型。对你而言,这可能是@section

= form_for @section do |f|