Complex forms often lead to complex controllers, but that doesn't have to be the case. In this episode see how you can create multiple models through a single form while keeping the controller clean.
# 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
# models/project.rb
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
<!-- 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 %>
本文介绍了一种通过单一表单创建多个模型的方法,并保持控制器简洁。通过示例代码展示了如何在Rails应用中实现这一过程,包括如何构建任务并将其关联到项目。
704

被折叠的 条评论
为什么被折叠?



