Flexible Association Managers in Rails 7 APIs

Adding association management methods to Rails models

Sebastian Scholl
3 min readSep 7, 2023
Photo by Transly Translation Agency on Unsplash

If you’re a Rails developer, you’re probably familiar with updating associated records through the association_name_ids= setter method. That strategy works well, but often leads to cluttered controller methods for managing record associations.

In a current project, I found myself wanting a more convenient interface for add, removing, and resetting record associations. So here is my implementation, where I added connect_*, disconnect_*, reconnect_* to relevant models. With them implemented, the following API calls do exactly what you’d expect 🙃

// Add a new record to a has_many collection (without removing existing ones)
api.put('/authors/1', {
"item": {
"connect_posts": [1, 8]
}
})

// Remove a record from a has_many collection (leaving all others be)
api.put('/authors/1', {
"item": {
"disconnect_posts": [9]
}
})

// Remove all records from a has_many collection and replace with new ones.
api.put('/authors/1', {
"item": {
"reconnect_posts": [2,3]
}
})

// Perform multiple operations in one call.
api.put('/authors/1', {
"item": {
"manage": {
"connect": [1, 8],
"disconnect": [9],
"reconnect": [2,3]
}
}
})

Creating an ActiveSupport::Concern

--

--