I have 2 Mongoid models that look something like this:
class User
include Mongoid::Document
field :name, type: String
embeds_many :jobs
end
class Job
include Mongoid::Document
field :title, type: String
embedded_in :user
end
This allows me to do something like
user.jobs.create(title: 'Test Job')
However, I'd like to be able to have some predefined jobs for a user to choose from, which would then be embedded in the user's document. Something like this:
Job.create(title: 'Predefined Job')
user.jobs << Job.first
However, creating a job on it's own throws the following error
Cannot persist embedded document Role without a parent document.
I'm kind of new to Mongoid, and can't find any examples of this in the documentation. Anyone know how you would do this?
Cannot persist embedded document Role without a parent document.
As the error clearly states embedded document
can only be embedded within another document. It cant exist as its own. If you wanted to make a Role independent from user, you need change the relation to has_many
from embeds_many
class User
include Mongoid::Document
field :name, type: String
has_many :jobs
end
class Job
include Mongoid::Document
field :title, type: String
belongs_to :user
end
so you can
Job.create(title: 'Predefined Job')
user.jobs << Job.first
and
job = Job.new(title: 'Predefined Job')
job.save
or if you still wanted to go ahead with embed_many
relation, you need to make a separate document to store the predefined jobs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With