I have a class structure like this:
class Parent < ActiveRecord::Base
has_one :child
accepts_nested_attributes_for :child
end
...
class Child < ActiveRecord::Base
belongs_to :parent
validates :text, :presence => true
end
In my mobile app (IOS + RestKit), I submit a HTTP POST request to create a new Parent object. This request has Content-Type application/json
The request looks like this on the wire:
{"parent":{"field1":"value1","child":{"text":"textvalue"},"duration":100}}
When Rails receives it, and tries to save it, I get the error:
ActiveRecord::AssociationTypeMismatch (Child(#2198796760) expected, got ActiveSupport::HashWithIndifferentAccess(#2158000780)):
Anyone know what’s going on?
To expand one what Sameer said, you need to send child_attributes instead of child. This means you can’t use the same mapping for pulling from the server and then pushing to it.
In RestKit you can specify a custom serialization that’s different from the original object mapping. Here’s an example that posts to a rails app, where Object has_many Images
Note that it’s also important to remove the ID attributes when posting – that gave me no end of trouble, since it doesn’t seem like it should matter in a post, but it throws rails off.
For what it’s worth, I also had issues parsing the nested objects with rails, and had to change my controller to look like this:
That could (and probably should) be moved into a before_create filter on the Object model.
I hope that helps in some way.