user3574603
user3574603

Reputation: 3618

Rails 5: Why can't I save nested attributes?

I'm struggling with understanding this.

I have two models Person and Address. Person accepts nested attributes for Address.

class Person < ApplicationRecord
  has_one :address, dependent: :destroy
  accepts_nested_attributes_for :address

I have a form app/views/person/new.html.erb:

<%= bootstrap_form_for(@person) do |f| %>
  #...
  <%= f.fields_for :address do |ff| %>
    <%= ff.text_field :apartment_number %>
    <%= ff.text_field :building_name %>
    <%= ff.text_field :building_number %>
    <%= ff.text_field :street %>
    <%= ff.text_field :town %>
    <%= ff.text_field :postcode, required: true %>
  <% end %>
#...

I have set up my strong params and I create the new record as follows:

  def create
    @person = Person.new(safe_params)

    if @person.save
      binding.pry
    else
      render 'new'
    end
  end

  private

  def safe_params
    params.require(:person).permit(
      :name,
      :date_of_birth,
      address: %i[
        apartment_number
        building_name
        building_number
        street
        town
        postcode
      ]
    )
  end

However, there's two things going on here. If @person fails validation, the re-rendered new view does not contain the submitted address data. Secondly, if the save is successful I can see that the associated address is not created:

@person.address
=> nil

What do I need to do to ensure that an address is created and saved? Have I misunderstood something obvious?

Upvotes: 0

Views: 31

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

As per the docs on nested attributes the strong parameters have to end with _attributes

params.require(:person).permit(
  :name,
  :date_of_birth,
  address_attributes: %i[ apartment_number ]
)

Upvotes: 1

Related Questions