Ruby on rails 是否可以使用Rails+MongoDB/Mongoid和JSON创建模型和子模型?

Ruby on rails 是否可以使用Rails+MongoDB/Mongoid和JSON创建模型和子模型?,ruby-on-rails,ruby,twitter,mongodb,mongoid,Ruby On Rails,Ruby,Twitter,Mongodb,Mongoid,例如,我想从以下JSON创建一个新的“Tweet”对象 {:for_user=>14248719, :message=>{:place=>nil, :user=>{:contributors_enabled=>false, :statuses_count=>217, :profile_use_background_image=>true, :friends_count=>3, :profile_background_color=>"C0DEE

例如,我想从以下JSON创建一个新的“Tweet”对象

{:for_user=>14248719, :message=>{:place=>nil, :user=>{:contributors_enabled=>false, :statuses_count=>217, :profile_use_background_image=>true, :friends_count=>3, :profile_background_color=>"C0DEED", :url=>nil, :following=>nil, :verified=>false, :profile_background_image_url=>"http://a3.twimg.com/a/1298748610/images/themes/theme1/bg.png", :time_zone=>nil, :favourites_count=>0, :profile_text_color=>"333333", :follow_request_sent=>nil, :profile_sidebar_fill_color=>"DDEEF6", :description=>"Lets get panda dev team rawk!", :id_str=>"95923128", :profile_background_tile=>false, :followers_count=>2, :created_at=>"Thu Dec 10 15:29:56 +0000 2009", :protected=>true, :profile_image_url=>"http://a2.twimg.com/profile_images/1121266473/panda01_normal.jpg", :is_translator=>false, :show_all_inline_media=>false, :geo_enabled=>false, :profile_link_color=>"0084B4", :location=>"Brighton", :name=>"letsgetpandadev", :listed_count=>0, :notifications=>nil, :profile_sidebar_border_color=>"C0DEED", :screen_name=>"letsgetpandadev", :id=>95923128, :lang=>"en", :utc_offset=>nil}, :favorited=>false, :coordinates=>nil, :text=>"another magic tweet", :in_reply_to_screen_name=>nil, :in_reply_to_user_id=>nil, :in_reply_to_status_id=>nil, :in_reply_to_status_id_str=>nil, :source=>"web", :contributors=>nil, :retweeted=>false, :in_reply_to_user_id_str=>nil, :id_str=>"44709765150015488", :retweet_count=>0, :created_at=>"Mon Mar 07 10:43:33 +0000 2011", :geo=>nil, :id=>44709765150015488, :entities=>{:urls=>[], :user_mentions=>[], :hashtags=>[]}, :truncated=>false}}
..并将“message”、“message.user”等保存为嵌入式子模型。 解析JSON并插入,只会生成一个“Tweet”对象,其哈希值保存在message属性中

我正在努力实现的目标可能吗?如果是,怎么做?如果没有,是否可以通过另一种方法实现

我正在为MongoDB使用Rails 3和Mongoid gem


谢谢

如果您希望消息是它自己的对象,那么您需要嵌入或引用定义它的另一个模型

class Tweet
  include Mongoid::Document

  embeds_one :message
end

class Message
  include Mongoid::Document

  embedded_in :tweet

  field :place
  ...
end

当您构建属性时,您将希望以与使用嵌套属性的表单post相同的方式构建属性,并设置您的模型以接受这些属性。

当然可以-但不能使用mongoid/mongomapper包装器。通过ruby驱动程序本身连接。。。本教程包含更多内容:


这看起来像一个ruby哈希,而不像JSON。也许可以把它转换成.to_jsonSorry,是的。我贴错东西了。这是在它从JSON解析成ruby哈希之后。好的,谢谢Paul。只是确认一下,不可能只插入一块JSON,我必须手动构造对象,或者至少操纵JSON来创建对象。。。即使在我的配置中设置了“allow\u dynamic\u fields:true”,在设置此关联后,一切似乎都正常。我想我希望这一切都是动态的,我不必建立这些协会。
require 'rubygems'
require 'mongo'

db = Mongo::Connection.new.db("mydb")
test_collection = db.collection("testCollection")

doc = {"name" => "MongoDB", "type" => "database", "count" => 1,
       "info" => {"x" => 203, "y" => 102}
      }
test_collection.insert(doc)