2012-11-22 103 views
2

我有2類...文章和評論(這是嵌入文章)。Mongoid如何插入嵌入式記錄?

class Article 
    include Mongoid::Document 
    field :name, type: String 
    field :content, type: String 
    field :published_on, type: Date 

    validates_presence_of :name 

    embeds_many :comments 
end 

,另一個

class Comment 
    include Mongoid::Document 
    field :name, type: String 
    field :content, type: String 

    embedded_in :article, :inverse_of => :comments 
end 

本MongoDB的文檔的JSON表示爲:

{ 
    _id:ObjectId("50ae35274b6b5eaa77000001"), 
    author_id:ObjectId("50ae3b1e4b6b5e8162000001"), 
    comments:[ 
     { 
     _id:ObjectId("50ae380e4b6b5e0c34000001"), 
     name:"fak", 
     content:"i like this article 
     } 

    ], 
    content:"article about nothing", 
    name:"my sweet article", 
} 

如何插入使用在軌道上mongoid本文檔中的另一條評論?

感謝 FAK

回答

4

我已經成功地做到這一點...

在評論控制器:

def create 
    @article = Article.find(params[:article_id]) 
    @comment = @article.comments.create!(params[:comment]) 
    redirect_to @article, :notice => "Comentario criado!" 
end 

然後我找到我想要添加評論的對象...並創建它

@photox=Photo.find_by(name: "foto xpto") 
@photox.comments.create(:comment=>"NOVO COMENTARIO") 

謝謝你們......