2011-03-07 75 views
0

例如,我想從以下JSON是否可以使用Rails + MongoDB/Mongoid和JSON創建模型和子模型?

{: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}} 

創建一個新的「分享Tweet」對象..和有「消息」,「message.user」等保存爲嵌入式兒童模特。 解析JSON並插入,只會產生一個'Tweet'對象,並在消息屬性中保存一個散列值。

是我正在努力實現的可能嗎?如果是這樣,怎麼樣?如果沒有,是否有可能通過另一種方法?

我正在使用Rails 3和MongoidDB的Mongoid Gem。

感謝

+0

這看起來像一個紅寶石哈希,而不是像JSON。也許用'.to_json'轉換它。 – sled 2011-03-07 14:34:38

+0

對不起,是的。我貼錯了東西。這是從JSON解析成紅寶石哈希之後。 – kombinat 2011-03-07 15:40:29

回答

0

當然你可以 - 只是不與mongoid/mongomapper包裝。通過紅寶石驅動程序本身連接...本教程有更多: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) 
0

如果您希望消息是自己的對象,那麼你要麼需要嵌入或引用另一個模型定義它。

class Tweet 
    include Mongoid::Document 

    embeds_one :message 
end 

class Message 
    include Mongoid::Document 

    embedded_in :tweet 

    field :place 
    ... 
end 

當你創建的屬性,你將要構建它們你將一個表格後嵌套屬性和建立模型來接受他們的方式相同的方式。

+0

好的,謝謝保羅。只是爲了確認,不可能僅僅是在一堆JSON中查找,我將不得不手動構造對象,或者至少操縱JSON來創建對象......即使我有'allow_dynamic_fields:true'集在我的配置? – kombinat 2011-03-07 14:58:10

+0

建立這種關聯後,一切似乎都奏效了。我想我希望它可以都是動態的,我不需要建立這些關聯。 – kombinat 2011-03-07 15:41:16

相關問題