Created
July 5, 2012 22:21
-
-
Save latortuga/3056848 to your computer and use it in GitHub Desktop.
Nested forms for children and relationships
This file contains hidden or 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
| # 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 |
This file contains hidden or 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
| <!-- 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