DynamoDB Dynomite Has And Belongs To Many

Example:

app/models/user.rb

class User < ApplicationItem
  has_and_belongs_to_many :groups
end

There is should be corresponding has_and_belongs_to_many as the inverse relationship.

app/models/group.rb

class Group < ApplicationItem
  belongs_to :user
end

Note: For the test data set below, the id are set to friendly names to help explain. Here’s how to create the Test Data Set.

When both regular and inverse relationships are defined, Dynomite will update both “foreign key” fields.

Creating

bob = User.find("bob")
bob.groups << Group.find("group-red")
bob.groups << Group.find("group-green")
kevin = User.find("kevin")
kevin.groups << Group.find("group-red")

This will store the ids in the users.group_ids and groups.user_ids fields as String Set types.

If you’re coming from the relational database world, you might be thinking, where’s the join table? There is no join table. Each of the join columns are added to the existing tables. This corresponds more with how key-value schemaless databases like DynamoDB work.

Deleting

Deleting the posts with the association method will remove the “foreign keys” and also delete the Group records themselves.

bob = User.find("bob")
bob.groups.delete_all
Group.exists?("group-red")   # false
Group.exists?("group-green") # false
kevin = User.find("kevin")
kevin.groups # [] # group-red has been removed also

If you need to run callbacks.

bob.group.destroy_all

Disassociating

If you want to disassociate the items without deleting them.

red = Group.find("group-red")
green = Group.find("group-green")
bob.groups.disassociate(red, green)
bob.groups.include?(red)   # false
bob.groups.include?(green) # false

You can also disassociate all items.

bob.groups.disassociate_all

You can also reassociate all items completely.

bob.groups = Group.find("group-yellow", "group-blue")

Querying

You can do some basic filtering with has_and_belongs_to_many. See: Association Querying.