我有一个房东类,它有N个地址。 房东接受地址的嵌套属性 我有一个用于创建房东的表单,该表单是创建地址的子表单。
地址要求landlord_id有效,因此保存。
当我创建房东时如何创建地址而不必在房东控制器的create方法调用中保存房东两次?
landlord_controller.rb#创建
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
landlord / new.html.erb#form
<%= 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 %>
答案 0 :(得分:2)
当然,请使用find_or_initialize_by(...)
代替where(...).first_or_create
(或者,您可以保持相同的where
模式并使用first_or_initialize
)。然后使用assign_attributes
添加地址,最后尝试save
。正如@CodeGroover建议的那样,你可以稍微重构一下:
other_params = params[:landlord].slice!(:name, :city_id, :province_id)
@landlord = Landlord.find_or_initialize_by(params[:landlord])
@landlord.assign_attributes(other_params)
if @landlord.save
...