Search code examples
ruby-on-railsruby-on-rails-4nested-attributes

Nested Parameters, with polymorphic one-to-one


I'm having an issue, where I'm trying to add an Address to a Person, using a form on my #new-action, as usual.
What I'm doing currently, is

class Person < ActiveRecord::Base
  has_one :address, :as => :owner

  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  belongs_to :owner, :polymorphic => true
end

In my form, I'm using form_for @person do |f| - then the form, and then f.fields_for :address do |af| and the fields, using af.text_field.

My controller action:

def create
  person = Person.new(person_params)

  if person.valid?
    person.save
    redirect_to edit_content_person_path(@current_work_context, person)
  else
    @person = person
    render 'new'
  end
end

def person_params
    params.require(:person).permit( :name, :address => [:line_one, :line_two, :zipcode, :city])
end

When I submit my form, with these parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"blablabla==",
 "person"=>{"name"=>"mr man",
 "address"=>{"line_one"=>"test address 15",
 "line_two"=>"",
 "zipcode"=>"2600",
 "city"=>"Glostrup"}},
 "locale"=>"da",
 "context_id"=>"9"}

Yet, I get the exception: ActiveRecord::AssociationTypeMismatch

Address(#70198415678880) expected, got ActionController::Parameters(#70198414055220)

I cannot seem to figure out why.

EDIT - My view, simplified:

<%= form_for @person do |f| %>

  <%= f.text_field :name %>

  <%= f.fields_for :address do |af| %>
    <%= af.label :address %>
    <%= af.text_field :line_one, :placeholder => "Address 1" %>
    <%= af.text_field :line_two, :placeholder => "Address 2" %>

    <%= af.label :zipcode %>
    <%= af.text_field :zipcode, :class => "form-control" %>

    <%= af.label :city %>
    <%= af.text_field :city, :class => "form-control" %>

  <% end %>

<% end %>

Solution

  • let trys one thing. Please and this lines and restart your server

    # config/initializers/inflections.rb
    
    ActiveSupport::Inflector.inflections do |inflect|'
      inflect.irregular 'address', 'addresses'
    end
    

    edit

    # after we discussing more about the problem in chat we found the solution. 
    # The object 'Person' not initialize correctly to f.fields_for :address
    
    # view
    
    <% f.object.build_address if f.object.address.blank? %> #add this line 
    <%= f.fields_for :address do |af| %>