Created
November 6, 2011 18:44
-
-
Save zapatoche/1343296 to your computer and use it in GitHub Desktop.
nested models in rails 3
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/survey.erb | |
class Survey < ActiveRecord::Base | |
has_many :questions, :dependent => :destroy | |
accepts_nested_attributes_for :questions | |
validates_presence_of :name | |
end | |
/models/question.erb | |
class Question < ActiveRecord::Base | |
belongs_to :survey | |
validates_presence_of :content | |
end | |
/controllers/surveys_controller.rb | |
def new | |
@survey = Survey.new | |
@survey.questions.build | |
respond_to do |format| | |
format.html # new.html.erb | |
format.json { render json: @survey } | |
end | |
end | |
/views/survey/_form.html.erb | |
<%= form_for(@survey) do |f| %> | |
<% if @survey.errors.any? %> | |
<div id="error_explanation"> | |
<h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2> | |
<ul> | |
<% @survey.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> | |
<h3>Add new question</h3> | |
<% f.fields_for :questions do |p| %> | |
<%= p.label :content, "Questions" %><br /> | |
<%= p.text_area :content, :rows => 3 %> | |
<% 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