Rails:Field被定义为(n)数组,但收到了一个ActiveSupport :: HashWithIndifferentAccess

时间:2011-02-03 04:02:54

标签: ruby-on-rails mongodb mongoid

我已经创建了Post和TagObject模型,如下所示

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

并且当前有一个页面向Post控制器的更新方法提交PUT。更新失败,我在WEBrick控制台中获得以下内容。

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::InvalidType (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'

我完全不知道如何修复它,我们将非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

是的,似乎问题在于它正在尝试

tags = {0=>'testingdfg'}

而不是

tags[0] = 'testingdfg'

并设置它的内容,就像我期待的那样。我刚刚在update方法中添加了一些逻辑来实现,并且它工作正常。

答案 1 :(得分:0)

在模型中,输入

field :tags, :type => Hash

而不是

field :tags, :type => Array