Skip to content

Instantly share code, notes, and snippets.

@latortuga
Created July 5, 2012 22:21
Show Gist options
  • Select an option

  • Save latortuga/3056848 to your computer and use it in GitHub Desktop.

Select an option

Save latortuga/3056848 to your computer and use it in GitHub Desktop.
Nested forms for children and relationships
# Models
class Child
has_many :relationships
end
class RelationType
has_many :relationships
end
class User
has_many :relationships
end
class Relationship
belongs_to :relation_type
belongs_to :user
belongs_to :child
accepts_nested_attributes_for :relationships
end
# Controller
class RelationshipsController
def new
@relationship = current_user.relationships.new
end
def create
@relationship = current_user.relationships.new(params[:relationship])
@relationship.save
end
end
<!-- New child -->
<%= form_for @relationship do |f| %>
<%= f.input :relation_type %> # defaults to a select
<%= f.simple_fields_for :child do |cf| %>
<%= cf.input :name %>
<%= etc %>
<% end %>
<% end %>
<!-- Child already exists -->
<%= form_for @relationship do |f| %>
<%= f.input :relation_type %> # defaults to a select
<%= f.input :child %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment