Search code examples
ruby-on-railsrubysimple-form

Rails 4 Nested Forms Simple_form_for & simple_field_for


I'm just trying to generate a simple nested form, like so:

<%= simple_form_for @profile do |f| %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :phone_number %>
<%= f.simple_fields_for :addresses do |p| %>
  <%= p.input :street %>
  <%= p.input :city %>
  <%= p.input :state, collection: us_states %>
  <%= p.input :zip_code %>
<% end %>
<%= f.button :submit %>

My models:

class Profile < ActiveRecord::Base
  belongs_to :customer
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
  belongs_to :profile
end

My controller:

class ProfilesController < ApplicationController
  before_action :authenticate_customer!

  def new
    @profile = Profile.new
  end
end

Unfortunately that nested attribute addresses doesn't populate anything on the page, I would expect to see fields like street or city but I get nothing.

However, if I change <%= f.simple_fields_for :addresses do |p| %> to <%= f.simple_fields_for :address do |p| %> the fields display correctly.

Unfortunately doing this causes issues because I can't use the accepts_nested_attributes_for helper as outlined in the docs (as far as I can tell). Any idea why this isn't working?


Solution

  • The solution was to build the profile and the addresses in the #new action for it to work. Revised working code:

    class ProfilesController < ApplicationController
      before_action :authenticate_customer!
    
      def new
        @profile = current_customer.build_profile
        @profile.addresses.build
      end
    end
    

    You'll need to look at how your params come through, but since I have a has_many, they came through hashed with a key of a record id.