2015-07-03 26 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