1

我有一个地主类,它有 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 %>
4

1 回答 1

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
  ...
于 2013-10-04T13:34:45.720 回答