2013-10-04 88 views
1

我有一個房東類,它有N個地址。 房東接受地址的嵌套屬性 我有一個窗體,用於創建該窗體的房東是創建地址的子窗體。從父創建方法內創建嵌套模型

該地址要求房東標識符有效,因此保存。

當我創建房東時,如何創建地址而不必在房東控制器中的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 

房東/ 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 %> 
+1

其實,第二個'@ landlord.save'保存地址。如果你不想這樣做,你可以分別保存每個「地址」。 –

+0

在您的經驗中哪種方法更具優勢? – Derptacos

回答

2

當然,使用的where(...).first_or_createfind_or_initialize_by(...)而不是(或者,你可以保持相同的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 
    ... 
+0

迷你重構:Landlord.find_or_initialize_by(params [:landlord]) – CodeGroover

+0

然後可能params [:房東] .except(:地址) – CodeGroover

+1

@CodeGroover:排序,除了你想限制它的搜索條件。我會妥協使用'切片'。 – PinnyM