来看一个典型的场景,Project这个Model的new表单,我们需要在创建Project对象时也创建一些Task对象
我们可以使用fields_for这个标签:
[code]
<!-- 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 %>
[/code]
这里我们使用fields_for来为@project的每个task构建一个伪表单,实际上还是@project最外层同一个表单,不过这样我们就
可以在同一表单里添加额外的Model对象字段,再看一个官方的例子:
[code]
<% 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 %>
[/code]
然后我们在Project这个Model里添加task_attributes=方法:
[code]
# models/.projects.rb
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
[/code]
这样,我们的controller里的create方法没有受到任何“污染”:
[code]
# 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
[/code]
我们可以使用fields_for这个标签:
[code]
<!-- 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 %>
[/code]
这里我们使用fields_for来为@project的每个task构建一个伪表单,实际上还是@project最外层同一个表单,不过这样我们就
可以在同一表单里添加额外的Model对象字段,再看一个官方的例子:
[code]
<% 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 %>
[/code]
然后我们在Project这个Model里添加task_attributes=方法:
[code]
# models/.projects.rb
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
[/code]
这样,我们的controller里的create方法没有受到任何“污染”:
[code]
# 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
[/code]