My models
I’m trying to create a form for an Annotation. This annotation belongs to a Map, and each annotation should have one Boundary. A map can have many annotations.

I first created the association by letting both Annotation and Map has_one Boundary, but later I switched to using a polymorphic boundary_object. The error was the same regardless.
has_one :boundary, :as => :boundary_object # <= Map
has_one :boundary, :as => :boundary_object # <= Annotation
belongs_to :boundary_object, :polymorphic => true # <= Boundary
Views and Controller
Here’s the thing: First I used Boundary.new to create a new boundary object here, since I didn’t have a pre-set annotation object, since the form can be submitted multiple times.
maps/show.html.erb
<%= form_for([@map, Annotation.new], :remote => true ) do |f| %>
<%= f.text_area :body, :cols => 80, :rows => 10, :style => "width: 500px" %>
<%= f.fields_for Boundary.new do |b| %>
<%= b.text_field :ne_x, :style => "display:none" %>
<%= b.text_field :ne_y, :style => "display:none" %>
<%= b.text_field :sw_x, :style => "display:none" %>
<%= b.text_field :sw_y, :style => "display:none" %>
<% end %>
<% end %>
I could use f.fields_for :boundary too, if I have this in the maps_controller.rb:
@annotation = @map.annotations.build
@annotation.boundary = Boundary.new
But the result is still the same.
annotations_controller.rb
def create
@annotation = Annotation.new(params[:annotation])
respond_to do |format|
if @annotation.save
format.js { }
end
end
The Error
When submitting that form, this results in the following error at the first line in the create method.
ActiveRecord::AssociationTypeMismatch (Boundary(#2158793660) expected, got ActiveSupport::HashWithIndifferentAccess(#2165684420))
Obviously, the form works without the whole boundary thing. These are the parameters submitted:
{
"utf8"=>"✓",
"authenticity_token"=>"6GDF6aDc6GMR3CMP+QzWKZW9IV9gSxfdkxipfg39q7U=",
"annotation"=>
{
"body"=>"foo bar",
"boundary"=>
{
"ne_x"=>"11312",
"ne_y"=>"5919",
"sw_x"=>"6176",
"sw_y"=>"1871"
}
},
"map_id"=>"1"
}
What do I have to do to be able to create the Boundary object for this annotation right away?
According to your associations:
First, you need to build a new boundary object (see here for more info):
Second, you need to edit your view:
Third, check that you have accepts_nested_attributes_for for your Boundary in the Annotation model.
The form will then look like this – note that the name of the association needs
_attributes: