Rails: Field was defined as a(n) Array, but received a ActiveSupport::HashWithIndifferentAccess
I've created a Post and a TagObject model as follows
class Post
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :tag_objects
#embeds_many :comments
references_one :uploader, :class_name => 'User'
mount_uploader :image, ImageUploader
validates_presence_of :image
attr_accessible :tag_objects, :image
end
class TagObject
include Mongoid::Document
field :name
field :tags, :type => Array
embedded_in :post, :inverse_of => :tag_objects
attr_accessible :name, :tags
end
and currently have a page submit a PUT to the update method of the Post controller. The update fails and I get the following in the WEBrick console.
Started POST "/posts/4d4a174fa729cf71c70000a8" for 127.0.0.1 at Wed Feb 02 21:52:09 -0500 2011
Processing by PostsController#update as HTML
Parameters: {"post"=>{"tag_objects"=>{"1"=>{"tags"=>{"1"=>"testingfds"}}}}, "authenticity_token"=>"OZ+eXzD5NyqUI4CzPadlFUMDwRrg4LsaQBs5i+J65tU=", "id"=>"4d4a174fa729cf71c70000a8"}
honeycomb_development['posts'].find({:_id=>BSON::ObjectId('4d4a174fa729cf71c70000a8')}, {}).limit(-1)
Completed in 2ms
Mongoid::Errors::Invalid开发者_C百科Type (Field was defined as a(n) Array, but received a ActiveSupport::HashWithIndifferentAccess with the value {"1"=>"testingfds"}.):
app/controllers/posts_controller.rb:39:in `update'
I have absolutely no idea how to fix it and any help would be greatly appreciated.
Yah, seems the problem was that it was trying to do
tags = {0=>'testingdfg'}
instead of doing
tags[0] = 'testingdfg'
and set it's contents like I was expecting. I just added some logic into the update method to do so, and it works fine.
In the model, put
field :tags, :type => Hash
instead of
field :tags, :type => Array
精彩评论