dboyd68
dboyd68

Reputation: 1104

Mongoid has_and_belongs_to_many inverse_of: :nil unexpected data

I have a collection of Tasks that relate back to themselfs

class Task
  include Mongoid::Document
  has_and_belongs_to_many :related_tasks , class_name: 'Task', inverse_of: :nil

In the monogo data I am looking for Parent task

{
"_id" : ObjectId(""),
"related_task_ids" : [
    ObjectId(""),
    ObjectId("")
],
}

And on the child task (nothing)

The parent tasks looks correct. But on the child task I get

{
"_id" : ObjectId(""),
"nil_ids" : [
    ObjectId("")
],
"related_task_ids" : [ ],
}

Where nil_ids is the parent id.

Why is it storing the nil_id's? and is there any way to stop this?

I want a 1..n relationship i.e a task has many children.

It's not a n..n relationship i.e. Children tasks don't have many parent tasks.

Upvotes: 1

Views: 1093

Answers (1)

Steve
Steve

Reputation: 15736

The reason you are seeing a nil_ids key on the child side of the association is that you have specified the :nil Ruby symbol rather than nil. So Mongoid is just interpreting this like any other symbol and creating a nils collection on the Task as the inverse of the related_tasks collection.

Try:

has_and_belongs_to_many :related_tasks , class_name: 'Task', inverse_of: nil

This should leave the related_task_ids in the parent task but not store the nil_ids on the children.

Upvotes: 2

Related Questions