我有一个地主类,它有 N 个地址。房东接受地址的嵌套属性我有一个用于创建房东的表单,该表单是用于创建地址的子表单。
该地址需要一个有效的房东 ID,因此可以保存。
在创建房东时如何创建地址而不必在房东控制器的create方法调用中两次保存房东?
房东控制器.rb#create
def create
#check if a landlord of the same name already exists and load that instead
@landlord = Landlord.where(:name => params[:landlord][:name], \
:city_id => params[:landlord][:city_id], \
:province_id => params[:landlord][:province_id]).
first_or_create
if @landlord.save
flash[:success] = #"Thank you for submitting a Landlord "
#@landlord.addresses.build ....
#@landlord.save
redirect_to @landlord
else
render :new
end
end
楼主/new.html.erb #表格
<%= form_for @landlord do |f| %>
<%= f.fields_for :address do |address_form| %>
<%= address_form.label :number %>
<%= address_form.text_field :number %>
<%= address_form.label :street %>
<%= address_form.text_field :street %>
<%= address_form.label "#{:unit}# / Apt #" %>
<%= address_form.text_field :unit %>
<%= address_form.label :postal %>
<%= address_form.text_field :postal %>
<% end %>
<% end %>