2012-02-29 61 views
1

OK,刚:Mongoid:保存父模型不会保存HAS_ONE例如

class User 
    include Mongoid::Document 
    # devise stuff... 
    has_one :card 
end 

class Card 
    include Mongoid::Document 

    belongs_to :user 
end 


irb(main):012:0> user = User.new(email: "[email protected]", password: "testtest",password_confirmation: "testtest") 
=> #<User _id: 4f4e1b1494b3023d34000003, _type: nil, email: "[email protected]", encrypted_password: "$2a$10$yCdmjfgK94VrIec062ZXFuoTuApFFaFsDSOVEutoklcSGc4SQH2MG", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil> 
irb(main):013:0> user.build_card uuid: "test" 
=> #<Card _id: 4f4e1b2094b3023d34000004, _type: nil, created_at: nil, updated_at: nil, uuid: "test", user_id: BSON::ObjectId('4f4e1b1494b3023d34000003')> 
irb(main):014:0> user.new_record? 
=> true 
irb(main):015:0> user.card.new_record? 
=> true 
irb(main):016:0> user.save 
=> true 
irb(main):017:0> user.card.new_record? 
=> true 
irb(main):018:0> User.count 
=> 1 
irb(main):019:0> Card.count 
=> 0 

谢谢!

回答

5

OK,我需要使用

has_one :card, autosave: true 
+0

如果我没有使用自动保存真实,我将如何保存user.card? – Alexandre 2012-11-16 11:55:56

0

是的,你需要有自动保存:真正的(不知道为什么,这个信息是他们的官方文档中失踪)