Created
June 8, 2010 01:37
-
-
Save nesquena/429492 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add a new child to this person | |
@person.children_attributes = [ { :name => 'Son' } ] | |
@person.children #=> [ <#Person: name: 'Son'> ] | |
@person.children.clear | |
# Add two new children to this person | |
@person.children_attributes = | |
[ { :name => 'Son' }, { :name => 'Daughter' } ] | |
@person.save | |
@person.children #=> [ <#Person: name: 'Son'>, <#Person: name: 'Daughter'> ] | |
# Edit the son (assuming id == 1) | |
@person.children_attributes = [ { :id => 1, :name => 'Lad' } ] | |
@person.save | |
#=> the son's name is now 'Lad' | |
# Edit the daughter (id == 2) and add a new offspring | |
@person.children_attributes = | |
[ { :id => 2, :name => 'Lassie' }, { :name => 'Pat' } ] | |
@person.save | |
#=> the daughter's name is now 'Lassie' and there's a new offspring called 'Pat' | |
# Remove Pat (id = 3), we don't like him/her | |
@person.children_attributes = [ :id => 3, '_delete' => '1' } ] | |
@person.save | |
#=> Pat is now deleted |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% form_for @person do |person_form| %> | |
<%= person_form.label :name %> | |
<%= person_form.text_field :name %> | |
<% person_form.fields_for :children do |child_form| %> | |
<%= child_form.label :name %> | |
<%= child_form.text_field :name %> | |
<% unless child_form.object.new_record? %> | |
<%= child_form.check_box '_delete' %> | |
<%= child_form.label '_delete', 'Remove' %> | |
<% end %> | |
<% end %> | |
<%= submit_tag %> | |
<% end %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person < ActiveRecord::Base | |
validates_presence_of :name | |
has_many :children, :class_name => 'Person' | |
accepts_nested_attributes_for :children, :allow_destroy => true | |
# can also be used on has_one etc.. associations | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment