嵌套的一对一属性不会通过表单保存

时间:2016-12-08 19:00:06

标签: ruby-on-rails

我有一个带有嵌套一对一属性的表单,我无法保存到数据库中。我已经读了四个小时的SO线程试图解决它:

Contact.rb:
class Contact < ApplicationRecord

  has_one :address
  accepts_nested_attributes_for :address

end


Address.rb
class Address < ApplicationRecord

  belongs_to :contact

end


Routes.rb
Rails.application.routes.draw do

  resources :contacts do
    resources :addresses
  end

  root :to => 'contacts#index'

end


The form
<%= form_for @contact do |f| %>

  <div class="field">
    <%= f.label :firstname %>
    <%= f.text_field :firstname %>
  </div>

  <div class="field">
    <%= f.label :lastname %>
    <%= f.text_field :lastname %>
  </div>

  <%= f.fields_for :address do |address_fields| %>
    <%= address_fields.label :streetname %>
    <%= address_fields.text_field :streetname %>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>

<% end %>


Controller:
class ContactsController < ApplicationController
  before_action :find_contact, only: [:show, :edit, :update, :destroy]

  def index
    @contacts = Contact.all
  end

  def show
  end

  def new
    @contact = Contact.new
    @ontact.build_address
  end

  def create
    @contact = Contact.new(contact_params)

    if @contact.save
      redirect_to @contact
    else
      render 'new'
    end
  end


  (...)

  private

    def find_contact
      @contact = Contact.find(params[:id])
    end

    def contact_params
      params.require(:contact).permit(:firstname, :lastname, 
                            address_attributes: [:contact_id, :streetname])
    end

end

使用上面的代码,不会保存任何内容并回滚事务。早些时候,只保存了联系人详细信息,而地址仍为零,以下行给出了错误&#34; streetname&#34;未知:

<p><%= @contact.address.streetname %></p>

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

感谢@fbelanger带领我找到解决方案:

我注意到“params”的内容允许被设置为false。我通过Google发现Rails 5需要在地址模型中添加以下内容到belongs_to行:

class Address < ApplicationRecord
  belongs_to :contact, required: false
end

现在它被保存了:欢呼!