Created
February 2, 2012 04:05
-
-
Save danvine/1721375 to your computer and use it in GitHub Desktop.
2 models updated from 1 form view using rails 3.2.1
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
### Setup | |
mkdir 2_models_1_view | |
rails new 2_models_1_view | |
rails g scaffold Parent name:string age:integer | |
rails g scaffold Children toy:string hair:string eyes:string parent_id:integer | |
rake db:migrate | |
### models/parents.rb | |
class Parent < ActiveRecord::Base | |
attr_accessible :name, :age, :children_attributes | |
has_many :children | |
accepts_nested_attributes_for :children, :allow_destroy => true | |
end | |
### models/children.rb | |
class Child < ActiveRecord::Base | |
belongs_to :parent | |
end | |
### parents_controller.rb | |
# GET /parents/new | |
# GET /parents/new.json | |
def new | |
@parent = Parent.new | |
@parent.children.build | |
respond_to do |format| | |
format.html # new.html.erb | |
format.json { render json: @parent } | |
end | |
end | |
### views/parents/_form.html.erb | |
<%= form_for(@parent) do |f| %> | |
<% if @parent.errors.any? %> | |
<div id="error_explanation"> | |
<h2><%= pluralize(@parent.errors.count, "error") %> prohibited this parent from being saved:</h2> | |
<ul> | |
<% @parent.errors.full_messages.each do |msg| %> | |
<li><%= msg %></li> | |
<% end %> | |
</ul> | |
</div> | |
<% end %> | |
<div class="field"> | |
<%= f.label :name %><br /> | |
<%= f.text_field :name %> | |
</div> | |
<div class="field"> | |
<%= f.label :age %><br /> | |
<%= f.number_field :age %> | |
</div> | |
<%= f.fields_for :children do |xxx| %> | |
<hr /> | |
<%= xxx.label :toy, "toy" %><br /> | |
<%= xxx.text_area :toy %><br /> | |
<% end %> | |
<div class="actions"> | |
<%= f.submit %> | |
</div> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment