· 2 min read
Screencast: Formulare mit verschachtelten Modellen
Download:
Download (22.4 MB, 11:09) Alternativer Download für iPod & Apple TV (15.2 MB, 11:09)
Resourcen:
Quellcode:
[bash] rails surveysays script/generate nifty_layout script/generate nifty_scaffold survey name:string script/generate model question survey_id:integer content:text script/generate model answer question_id:integer content:string rake db:migrate [/bash]
[ruby] # models/survey.rb class Survey < ActiveRecord::Base has_many :questions, :dependent => :destroy accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true end
# models/question.rb class Question < ActiveRecord::Base belongs_to :survey has_many :answers, :dependent => :destroy accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true end
# models/answer.rb class Answer < ActiveRecord::Base belongs_to :question end
# surveys_controller.rb def new @survey = Survey.new 3.times do question = @survey.questions.build 4.times { question.answers.build } end end [/ruby]
[html] <% form_for @survey do |f| %> <%= f.error_messages %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.submit “Submit” %>
<% end %><%= f.label :content, "Question" %>
<%= f.text\_area :content, :rows => 3 %>
<%= f.check\_box :\_destroy %> <%= f.label :\_destroy, "Remove Question" %>
<%= f.label :content, "Answer" %> <%= f.text\_field :content %> <%= f.check\_box :\_destroy %> <%= f.label :\_destroy, "Remove" %>
\[/html\]