Project这个Model的new表单,我们需要在创建Project对象时也创建一些Task对象
我们可以使用fields_for这个标签:
- <!--?new.rhtml?-->??
- <%?form_for?:project,?:url?=>?projects_path?do?|f|?%>??
- ??<p>??
- ????Name:?<%=?f.text_field?:name?%>??
- ??</p>??
- ??<%?for?task?in?@project.tasks?%>??
- ????<%?fields_for?"project[task_attributes][]",?task?do?|task_form|?%>??
- ??????<p>??
- ????????Task:?<%=?task_form.text_field?:name?%>??
- ??????</p>??
- ????<%?end?%>??
- ??<%?end?%>??
- ??<p><%=?submit_tag?"Create?Project"?%></p>??
- <%?end?%>??
这里我们使用fields_for来为@project的每个task构建一个伪表单,实际上还是@project最外层同一个表单,不过这样我们就
可以在同一表单里添加额外的Model对象字段,再看一个官方的例子:
?
- <%?form_for?:person,?@person,?:url?=>?{?:action?=>?"update"?}?do?|person_form|?%>??
- ??First?name:?<%=?person_form.text_field?:first_name?%>??
- ??Last?name:?<%=?person_form.text_field?:last_name?%>??
- ??
- ??<%?fields_for?:permission,?@person.permission?do?|permission_fields|?%>??
- ????Admin??:?<%=?permission_fields.check_box?:admin?%>??
- ??<%?end?%>??
- <%?end?%>?
然后我们在Project这个Model里添加task_attributes=方法:
- #?models/.projects.rb??
- def?task_attributes=(task_attributes)??
- ??task_attributes.each?do?|attributes|??
- ????tasks.build(attributes)??
- ??end??
- end??
这样,我们的controller里的create方法没有受到任何“污染”:
- #?projects_controller.rb??
- def?new??
- ??@project?=?Project.new??
- ??3.times?{?@project.tasks.build?}??
- end??
- ??
- def?create??
- ??@project?=?Project.new(params[:project)??
- ??if?@project.save??
- ????flash[:notice]?=?"Successfully?created?project."??
- ????redirect_to?projects_path??
- ??else??
- ????render?:action?=>?'new'??
- ??end??
- end??
From: http://www.cnblogs.com/orez88/articles/1530286.html