Kerm1t
Kerm1t

Reputation: 31

Can't update or destroy embedded object on mongoid

i'm trying to update an embedded object on mongoid and terminal says true, but the change is not persisted on database.

This is the command

a = Post.first
b = Category.last
a.category = b
b.save <-- return true but no persist on db

When I try to change one single value of the embedded object says RuntimeError: can't modify frozen BSON::Document.

a.category.name = "test" <-- return RuntimeError: can't modify frozen BSON::Document.

Any ideas? I'm using mongoid 4.0

Post:

class Post
  include Mongoid::Document

  field :name, type: String
  field :intro, type: String
  field :content, type: String

  embeds_one :category

Category:

class Category  
  include Mongoid::Document

  field :name, type: String

Regards,

Upvotes: 0

Views: 1677

Answers (1)

sidegeeks
sidegeeks

Reputation: 1041

a = Post.first
b = Category.last
a.category = b
b.save <-- return true but no persist on db

You should be saving variable a instead of b, like this:

a.category = b
a.save #this would save the category id to post.

and NOW,

a.category.name = "test"

would work.

Upvotes: 1

Related Questions