Kaveh
Kaveh

Reputation: 421

Mongoid: model which belongs_to some model doesn't update

I got these two model:

class A
 include Mongoid::Document

 has_many :child, :class_name => "B", :inverse_of => :parent

 field :name
end

class B
  include Mongoid::Document

  belongs_to :parent, :class_name => "A", :inverse_of => :child

  field :name
end

p = A.new
p.name = "father"
c = B.new
c.name = "son"
c.save
p.child << c
p.save
c.save

When i create a child and set the parent, everything is just fine. If i create a child without specifying the parent and saving it, that works as well. But i can't uppdate the parent_id after saving child. I have tested these proccess in rails console and got no error.

Appreciate any idea that approach the solution.

Upvotes: 0

Views: 319

Answers (2)

Alexandr T
Alexandr T

Reputation: 1501

When you use new it's create instance, but not save in db. And when you set child for parent, mongoid validate relation via a validates_associated but it's not in db. Try use create instead new or

p.save

before set relation.

Upvotes: 1

Alexandr T
Alexandr T

Reputation: 1501

Try gem mongoid-ancestry for trees structure in db.
If you use it, changes will be minimal, but it's work

Upvotes: 1

Related Questions