DynamoDB Dynomite Has Many
Important: These docs are for the outdated Jets 5 versions and below. For the latest Jets docs: docs.rubyonjets.com
Example:
app/models/user.rb
class User < ApplicationItem
has_many :posts
end
There is typically a corresponding belongs_to as the inverse relationship.
app/models/post.rb
class Post < 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
user = User.find("bob")
user.posts << Post.find("post-1")
user.posts << Post.find("post-2")
user.posts.map(&:id).sort # ["post-1","post-2"]
This will store the ids in the users.posts_ids
field as a String Set and in the posts.user_id
field as a String.
user.posts_ids # <Set: {"post-1", "post-2"}>
Post.find("post-1").user_id # "bob"
Post.find("post-2").user_id # "bob"
Deleting
Deleting the posts with the association method will remove the “foreign keys” and also delete the Post records themselves.
user.posts.delete_all
Post.find_by(id: "post-1") # nil
Post.find_by(id: "post-2") # nil
If you need to run the callbacks.
user.posts.destroy_all
Disassociating
If you want to disassociate the items without deleting them.
user.posts.disassociate Post.find("post-1")
user.posts.disassociate Post.find("post-2")
Post.exists?("post-1") # true
Post.exists?("post-2") # true
You can also disassociate all items.
user.posts.disassociate_all
You can also reassociate all items completely.
user.posts = Post.find("post-1", "post-2")
Querying
You can do some basic filtering with has_many
. See: Association Querying.
Association with Same Model
class User < ApplicationItem
has_many :students, class: User
belongs_to :teacher, class_name: :user
has_and_belongs_to_many :friends, inverse_of: :friending_users
end