http://railscasts.com/episodes/74-complex-forms-part-2
http://railscasts.com/episodes/75-complex-forms-part-3
Ryan made a great introduction about having a form dealing with multiple models. Yet in Rails 2.3 due to popular demand, it is already bundled with this feature.
http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
http://stackoverflow.com/questions/818460/problems-with-nested-form-fields-showing-up
First of all, the model has to know about the nested attributes. With that the course can access the sections_attributes.
class Course < ActiveRecord::Base
has_many :sections
accepts_nested_attributes_for :sections
end
Then for the view at new.html.erb
<% form_for @course do |course_form| %>
<%= course_form.label :title %>
<%= course_form.text_field :title %>
<% course_form.fields_for :sections do |section_form| %>
<%= section_form.label :sec %>
<%= section_form.text_field :sec %>
<% end %>
<%= submit_tag %>
<% end %>
In the controller, there is a need to add @course.sections.build at the new action in order to populate the form and create the section together with the course in a hash.
def new
@course = Course.new
@course.sections.build
end
But, wait there is more... you might wanna add more sections dynamically... and i found a tutorial that just do that
http://railsforum.com/viewtopic.php?id=28447
0 comments:
Post a Comment