Skip to content

Attributes/Persistence logic does not support Mongoid HABTM #33

@Startouf

Description

@Startouf

In Mongoid, has_and_belongs_to_many means storing an array of IDs in the document.
So the usual flow of updating a model attribute with a key doesn't make too much sense. Instead we need to add/remove keys`

class Tag
  has_many :profiles
end

class Profile
  has_and_belongs_to :tags
end

tags = FactoryGirl.create_list(:tags, 2)
profile = Profile.create(tags: tags)
profile.as_document
#=>
 {
 "_id"=>BSON::ObjectId('593ab877aba9cf64dbd09582'),
 "tag_ids"=>[
    BSON::ObjectId('592da071aba9cf502513d424'), 
    BSON::ObjectId('592da081aba9cf502513d426')
  ]
}

To begin with, there is a somewhat hardcoded list of has_many/belongs_to in the persistence class
https://github.com/jsonapi-suite/jsonapi_compliable/blob/master/lib/jsonapi_compliable/util/persistence.rb#L98

that should be moved to the adapter, so for mongoid I can override/implement it with a :habtm

Then for the persistence flow itself, I had to monkeypatch the update_foreign_key logic to support writing the list of habtm IDs

def update_foreign_key(parent_object, attrs, x)
    ...
    elsif x[:sideload].type == :habtm
      (attrs[x[:foreign_key]] ||= []) << parent_object.send(x[:primary_key]).to_s
    ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions