2014-10-01 71 views
0

我有一個簡單的模型的Rails應用程序:Rails的4.0:保存HAS_ONE協會不起作用

客戶HAS_ONE地址

地址belongs_to的客戶

new.html.erb

<%=f .fields_for :address do |a| %> 
 
    <%=a .label :street %> 
 
    <br> 
 
    <%=a .text_field :street %> 
 
     <br> 
 

 
     <%=a .label :number %> 
 
     <br> 
 
     <%=a .text_field :number %> 
 
      <br> 
 

 
      <%=a .label :zipcode %> 
 
      <br> 
 
      <%=a .text_field :zipcode %> 
 
       <br> 
 

 
       <%=a .label :city %> 
 
       <br> 
 
       <%=a .text_field :city %> 
 
        <br> 
 

 
        <%=a .label :country %> 
 
        <br> 
 
        <%=a .text_field :country %> 
 
         <br> 
 
         <% end %>

customer_controller.rb

def create 
 
    @customer = Customer.new(customer_params) 
 
    @customer.save 
 
    redirect_to @customer 
 
end 
 
    
 
private 
 
def customer_params 
 
    params.require(:customer).permit(:ctype, :name, :dateOfBirth, :image, :custom1, :custom2, :custom3, :email, :phone, :mobilphone, :website, address_attributes:[:street, :number, :zipcode, :city, :country]) 
 
end

如果我創建一個新的客戶和地址我的地址不會被保存:(

你能可以幫助我嗎?

+3

你在模型中使用'accep_nested_attributes_for'嗎? – 2014-10-01 09:39:04

+0

運行'@ customer.save!'有什麼例外? – 2014-10-01 09:39:24

+0

nope我不使用accept_nested_attributes_for:/不聽我添加之前,我需要耙:回滾 - >耙db:遷移??,我沒有得到一個例外... – 2014-10-01 09:53:22

回答

0

您的客戶型號中缺少accepts_nested_attributes_for :address

它應該看起來像這樣,告訴rails您的代碼實際上正在更新其他模型。

class Customer < ActiveRecord::Base 
    has_one :address 
    accepts_nested_attributes_for :address 
end 

希望這會有所幫助。

+0

類客戶<的ActiveRecord :: Base的 \t的has_many:成員 \t HAS_ONE:地址 \t accepts_nested_attributes_for:地址 結束 是我的課你可以看到它已經...但它不工作:( – 2014-10-01 14:33:34

+0

@GeorgeKrause你做有一個客戶表格附上你的地址表格,不是嗎?另外,你可以嘗試在保存後檢查對象'@ customer'上的錯誤,看看是否有其他東西阻止保存。檢查錯誤http:// liahhansen .com/2011/04/15/rails-console-show-error-messages-for-all-attributes.html – Ron 2014-10-01 15:09:51

+0

我沒有得到任何錯誤... :-( – 2014-10-08 08:20:45