2015-07-03 73 views
1

我的对象是一个Section。每个部分可以有其他部分。 部分响应#index,索引返回其索引索引。 0如果一个部分没有兄弟节。在Rails中以嵌套形式更新子对象

假设我的数据结构是:

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> 

我在做什么错?

回答

1

在模型中添加这并获得成功:

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

accepts_nested_attributes_for :children 
+0

你的意思是模型? –

+1

是的,谢谢你纠正我! – Jack

0

form_for不应该采取集合,它应该只采取负责实现表单的行为的单一模型。对你而言,这可能是@section即。

= form_for @section do |f| 
+0

更新,更新后我收到新的错误消息。 – Jack

+0

然后你将不得不展示更多的代码,比如你在哪里设置'@ section' var(以及什么)。 – smathy