title: Rails 4 - Polymorphic associations
body: <p>I am trying to make an app in Rails 4.</p>
  
  <p>I have a profile model and an address model.</p>
  
  <p>the Associations are:</p>
  
  <p>profile.rb</p>
  
  <pre><code>has_many :addresses, as: :addressable
  </code></pre>
  
  <p>address.rb</p>
  
  <pre><code> belongs_to :addressable, :polymorphic =&gt; true
  </code></pre>
  
  <p>Address is a polymorphic model.</p>
  
  <p>I have an address form which has:</p>
  
  <pre><code>&lt;%= simple_form_for(@address) do |f| %&gt;
              &lt;%= f.error_notification %&gt;
  
              &lt;div class="form-inputs"&gt;
                  &lt;div class="row"&gt;
                      &lt;div class="col-xs-3"&gt;
                          &lt;%= f.input :unit %&gt;
                      &lt;/div&gt;
                      &lt;div class="col-xs-3 col-xs-offset-1"&gt;
                          &lt;%= f.input :street_number %&gt;
                      &lt;/div&gt;
                      &lt;div class="col-xs-3 col-xs-offset-1"&gt;
                          &lt;%= f.input :street %&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
  
                  &lt;div class="row"&gt;
                      &lt;div class="col-xs-3"&gt;
                          &lt;%= f.input :building %&gt;
                      &lt;/div&gt;
                      &lt;div class="col-xs-3 col-xs-offset-1"&gt;
                          &lt;%= f.input :city %&gt;
                      &lt;/div&gt;
                      &lt;div class="col-xs-3 col-xs-offset-1"&gt;
                          &lt;%= f.input :region %&gt;
                      &lt;/div&gt;
  
                  &lt;/div&gt;
  
                  &lt;div class="row"&gt;
                      &lt;div class="col-xs-3"&gt;
                          &lt;%= f.input :zip %&gt;
                      &lt;/div&gt;
                      &lt;div class="col-xs-3 col-xs-offset-1"&gt;
                          &lt;%= f.input :country, priority: [ "Australia", "New Zealand", "United Kingdom" ] %&gt;
                      &lt;/div&gt;
  
  
                  &lt;/div&gt;
  
                  &lt;div class="row"&gt;
                      &lt;div class="col-xs-3"&gt;
                          &lt;%= f.input :main_address %&gt;
                      &lt;/div&gt;
                      &lt;div class="col-xs-3 col-xs-offset-1"&gt;
                          &lt;%= f.input :project_offsite %&gt;
                      &lt;/div&gt;
  
  
                  &lt;/div&gt;
  
  
  
              &lt;/div&gt;
  
              &lt;div class="form-actions"&gt;
                  &lt;%= f.button :submit, :class =&gt; "formsubmit" %&gt;
              &lt;/div&gt;
              &lt;% end %&gt;
  </code></pre>
  
  <p>I try to create an address and save it. I then check that it is in the rails console. Something is going wrong because the rails console shows this:</p>
  
  <pre><code>#&lt;Address id: 1, unit: "", building: "", street_number: "34", street: "f", city: "sdfasdf", region: "asdf", zip: "2000", country: "GB", main_address: nil, project_offsite: nil, time_zone: nil, latitude: nil, longitude: nil, addressable_id: nil, addressable_type: nil, created_at: "2015-12-30 00:07:00", updated_at: "2015-12-30 00:17:00"&gt; 
  </code></pre>
  
  <p>The addressable id and the addressable type are both nil.</p>
  
  <p>They should have the references back to profile or wherever the related model is.</p>
  
  <p>Is there a step missing in setting up this process?</p>
  
  <p>This video (minute 3.40) says rails automatically handles filling out the type and id fields for polymorphic models.
  <a href="https://gorails.com/episodes/comments-with-polymorphic-associations?autoplay=1" rel="nofollow noreferrer">https://gorails.com/episodes/comments-with-polymorphic-associations?autoplay=1</a></p>
  
  <p>When I try to create a new address from the rails console, I type:</p>
  
  <pre><code>Address.create(addressable: Address.first, profile_id: "1", country: "AU")
  </code></pre>
  
  <p>The console error is:</p>
  
  <pre><code>ActiveRecord::UnknownAttributeError: unknown attribute 'profile_id' for Address
  </code></pre>
  
  <p>My address table has an addressable_id key and my profile model has has_many :addresses, as: :addressable</p>
  
  <p>I can't understand what causes the error </p>
  
  <p>ANOTHER ATTEMPT</p>
  
  <p>So, from what I gather from the suggestions below, I need to do something to let address know that it belongs to a profile. </p>
  
  <p>I also found this article which sets out an example of what needs to happen in the profiles controller to get things working with polymorphic associations:
  <a href="http://6ftdan.com/allyourdev/2015/02/10/rails-polymorphic-models/" rel="nofollow noreferrer">http://6ftdan.com/allyourdev/2015/02/10/rails-polymorphic-models/</a></p>
  
  <p>I change my new action in the profiles controller to (include addresses.build):</p>
  
  <pre><code> def new
      @profile = Profile.new
      @profile.qualifications.build
      @profile.visions.build
      @profile.personalities.build
      @profile.addresses.build
  
      authorize @profile
    end
  </code></pre>
  
  <p>I add nested attributes to my address association in the profile model:</p>
  
  <pre><code>has_many :addresses, as: :addressable
      accepts_nested_attributes_for :addresses,  reject_if: :all_blank, allow_destroy: true
  </code></pre>
  
  <p>I change my address form:
  -  from form_for to fields_for;
  -  rename it _address_fields.html.erb; and 
  - open the div tag with:</p>
  
  <pre><code>&lt;div class="nested-fields"&gt;
  </code></pre>
  
  <p>In my profiles form, I add the link to the form partial:</p>
  
  <pre><code>              Your addresss
              &lt;/div&gt;
              &lt;%= f.simple_fields_for :addresses do |f| %&gt;
  
                &lt;%= render 'addresses/address_fields', f: f %&gt;  
              &lt;% end %&gt;
              &lt;/div&gt;
            &lt;div class="row"&gt;
              &lt;div class="col-md-6"&gt;
  
                 &lt;%= link_to_add_association 'Add an address', f, :addresses, partial: 'addresses/address_fields' %&gt;
  
              &lt;/div&gt;
  </code></pre>
  
  <p>All of this is as set out in Jeiwan's answer on this post: <a href="https://stackoverflow.com/questions/34539157/rails-cocoon-gem-nested-forms">Rails - Cocoon gem - Nested Forms</a></p>
  
  <p>Then, when I try all of this, I get this error:</p>
  
  <pre><code>ActiveRecord::RecordNotUnique in ProfilesController#update
  PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_addresses_on_addressable_type_and_addressable_id" DETAIL: Key (addressable_type, addressable_id)=(0, 1) already exists. : INSERT INTO "addresses" ("unit", "building", "street_number", "street", "city", "region", "zip", "country", "addressable_id", "addressable_type", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"
  </code></pre>
  
  <p>The error points to the update method in the profiles controller:</p>
  
  <pre><code> def update
      respond_to do |format|
        if @profile.update(profile_params)
          format.html { redirect_to @profile }
          format.json { render :show, status: :ok, location: @profile }
        else
  </code></pre>
  
  <p>I found this post which describes a user's similar problem, but before i change the database, I'd like to try and understand what has happened.</p>
  
  <p><a href="https://stackoverflow.com/questions/11068800/rails-auto-assigning-id-that-already-exists">Rails auto-assigning id that already exists</a></p>
  
  <p>Another odd thing is when I look at the last address created in the console, it shows this:</p>
  
  <pre><code>#&lt;Address id: 6, unit: "", building: "", street_number: "34", street: "asdf", city: "asdf", region: "add", zip: "2111", country: "AU", main_address: nil, project_offsite: nil, time_zone: nil, latitude: nil, longitude: nil, addressable_id: 1, addressable_type: 0, created_at: "2016-01-01 22:01:31", updated_at: "2016-01-01 22:01:31"&gt;]&gt; 
  </code></pre>
  
  <p>The record now has an addressable_id but does not have an addressable_type. Is there something extra required to populate this field?</p>