Screencast: Formulare mit verschachtelten Modellen

Fomulare mit verschachtelten Modellen lassen sich viel einfacher mit der Methode accepts_nested_attributes erstellen. Wie diese Methode benutzt werden kann, zeigt Ryan in seinem dieswöchigen Screencast.

Be Sociable, Share!

Download:

Download (22.4 MB, 11:09)
Alternativer Download für iPod & Apple TV (15.2 MB, 11:09)

 

Resourcen:

Quellcode:

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
# 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
<!-- views/surveys/_form.html.erb -->
<% form_for @survey do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <% f.fields_for :questions do |builder| %>
    <%= render "question_fields", :f => builder %>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

<!-- views/surveys/_question_fields.html.erb -->
<p>
  <%= f.label :content, "Question" %><br />
  <%= f.text_area :content, :rows => 3 %><br />
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove Question" %>
</p>
<% f.fields_for :answers do |builder| %>
  <%= render 'answer_fields', :f => builder %>
<% end %>

<!-- views/surveys/_answer_fields.html.erb -->
<p>
  <%= f.label :content, "Answer" %>
  <%= f.text_field :content %>
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove" %>
</p>
Be Sociable, Share!

Eingestellt am 11.01.2010 um 10:30

Kategorie: Tutorials

Be Sociable, Share!

Kommentare für diesen Artikel wurden geschlossen.

Suchen auf rubyonrails.de

Aktuelle Rails Version + Abhängigkeiten:

Gem rails-3.0.0
actionmailer (= 3.0.0, runtime)
actionpack (= 3.0.0, runtime)
activerecord (= 3.0.0, runtime)
activeresource (= 3.0.0, runtime)
activesupport (= 3.0.0, runtime)
bundler (~> 1.0.0, runtime)
railties (= 3.0.0, runtime)

Rails auf Rubyforge
Rails auf Github