Rails 4.0:保存has_one关联不起作用

时间:2014-10-01 09:35:52

标签: ruby-on-rails model associations has-one

我有一个简单模型的rails应用程序:

客户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 %>
&#13;
&#13;
&#13;

customer_controller.rb

&#13;
&#13;
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
&#13;
&#13;
&#13;

如果我使用地址创建新客户,我的地址将不会保存:(

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您缺少客户模型中的accepts_nested_attributes_for :address

看起来应该是这样,告诉我们您的代码实际上正在更新其他模型。

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

希望这有帮助。

相关问题