2014-10-01 68 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