例如,我想从以下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'对象,并在消息属性中保存一个哈希值。
我想要实现的目标是什么?如果是这样,怎么样?如果没有,是否可以通过另一种方法?
我正在为MongoDB使用Rails 3和Mongoid gem。
由于
答案 0 :(得分:0)
如果您希望消息是它自己的对象,那么您需要嵌入或引用另一个定义它的模型。
class Tweet
include Mongoid::Document
embeds_one :message
end
class Message
include Mongoid::Document
embedded_in :tweet
field :place
...
end
构建属性时,您将希望以与具有嵌套属性的表单发布相同的方式构建它们,并将模型设置为以这种方式接受它们。
答案 1 :(得分:0)
当然可以 - 只是没有mongoid / mongomapper包装。通过ruby驱动程序本身连接......本教程有更多:http://api.mongodb.org/ruby/current/file.TUTORIAL.html
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)