user1801199
user1801199

Reputation: 61

How can I allow persisting without parent document with an embeds_many association?

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?

Upvotes: 6

Views: 2156

Answers (1)

RameshVel
RameshVel

Reputation: 65857

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

Upvotes: 7

Related Questions