开发者

Using awesome_nested_set in a nested form

I'm using Rails 3.0.7 with awesome_nested_set and I'm trying to create a nested form which will allow me to enter a category and sub categories all in one create form.

Here is my category model, controller & form

category.rb

class Category < ActiveRecord::Base
  acts_as_nested_set
end

categories_controller.rb

class CategoriesController < InheritedResources::Base
  def new
    @category = Category.new
    3.times { @category.children.build(:name => "test") }
  end
end

form

= form_for @category do |f|
    -if @category.errors.any?
        #error_explanation
            %h2= "#{pluralize(@category.errors.count, "error")} prohibited this category from being saved:"
            %ul
                - @category.errors.full_messages.each do |msg|
                    %li= msg

    .field
        = f.label :name
        = f.text_field :name

    %p Sub categories
    = f.fields_for :children do |child|
        = child.text_field :name

    .actions
     开发者_如何学运维   = f.submit 'Save'

The problem here is that I only end up with one sub category in my form and it doesn't have name set to 'test' so I don't believe that it's actually the child of the category showing here.

What am I missing here?

Can this be done?

Is there an easier way?

Update If I change my form to the following then it displays three sub categories each with name set to 'test'. This will not save correctly though.

%p Sub categories
- @category.children.each do |sub|
    = f.fields_for sub do |child|
        = child.label :name
        = child.text_field :name
        %br


Found my answer and wrote a wiki page about it here:

https://github.com/collectiveidea/awesome_nested_set/wiki/nested-form-for-nested-set

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜