Reputation: 1781
I got in trouble while designing data model.
I have master object "A" with its children "B", and "B" has many "C", but some "C" can also be free (not belong to any "B").
By standard mas_many/belongs_to Mongoid relationd foreign key stores in "C". And it's not so awful, it works fine even when it orphan, but I think it's not looks good. Is there any way make Mongoid to store children IDs in parent's list field?
Upvotes: 0
Views: 550
Reputation: 2096
For future viewers....
I ended using:
has_and_belongs_to_many
on Bbelongs_to
on CAnd in the before_add
callback from the has_and_belongs_to_many, I added something like object_to_add.c_id ||= self.id
. This way you can have the IDs listed in the parent.
Example with a Playlist with multiple Categories:
class Playlist
has_and_belongs_to_many :categories, before_add: :add_playlist_id, inverse_of: :playlist
private
def add_playlist_id(category)
category.playlist_id ||= id
end
end
class Category
belongs_to :playlist, inverse_of: :categories
end
Upvotes: 0
Reputation: 2061
What you describe sounds like belongs to many
and there is a way to achieve that by using has_and_belongs_to_many
relation on B class.
But in my opinion your initial approach is semantically better, but its up to you to choose.
Upvotes: 1