-
-
Notifications
You must be signed in to change notification settings - Fork 488
nested form for nested set
Joshua Kovach edited this page Feb 3, 2014
·
3 revisions
I wanted to create nested categories in the one form by using the nested model forms technique as described in Ryan's great Railscast http://railscasts.com/episodes/196-nested-model-form-part-1
Suppose I have a model category and it's using awesome_nested_set. When I go and create a new category I would like to have 3 sub categories built and I would like to create the main category and sub categories in one form.
Here is how I do that:
model
class Category < ActiveRecord::Base
acts_as_nested_set
accepts_nested_attributes_for :children
end
controller
class CategoriesController < InheritedResources::Base
def new
@category = Category.new
3.times { @category.children.build(:name => "test") }
end
end
My form
= form_for @category do |f|
.field
= f.label :name
= f.text_field :name
%p Sub categories
- @category.children.each do |sub|
= f.fields_for :children, sub do |child|
= child.label :name
= child.text_field :name
%br
.actions
= f.submit 'Save'
You can further adapt this with jQuery to make it easy to add/remove new entries, this is covered by Ryan in his Railscast.