I have a problem with relationships persisting in an embedded document. Here is the example
require 'mongoid'
require 'mongo'
class User
include Mongoid::Document
field :name
key :name
embeds_one :garage
end
class Garage
include Mongoid::Document
field :name
has_many :tools, autosave: true
has_many :cars, autosave: true
end
class Tool
include Mongoid::Document
belongs_to :garage, inverse_of: :tools
end
class Car
include Mongoid::Document
field :name
belongs_to :garage, inverse_of: :cars
end
When I run the following:
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("mydb")
end
connection = Mongo::Connection.new
connection.drop_database("mydb")
database = connection.db("mydb")
user = User.create!(name: "John")
user.build_garage
user.garage.cars << Car.create!(name: "Bessy")
user.save!
puts "user #{user}, #{user.name}"
user.garage.cars.each do |car|
puts "car is #{car}"
end
same_user = User.first(conditions: {name: user.name})
puts "same_user #{same_user}, #{same_user.name}"
same_user.garage.cars.each do |car|
puts "car found is #{car}"
end
the output is:
user #<User:0x00000003619d30>, John
car is #<Car:0x00000003573ca0>
same_user #<User:0x000000034ff760>, John
so the second time the user’s car array is not outputted. How do i get the array of cars to persist?
Thanks
You need to do a
user.garage.saveto save the embedded garage after you populate it.