Rails Dynamic Associations
Define your model associations in the database without changing the schema or models.
DEPRECATED
Use Adjustable Schema instead. It has a similar API, though it's not backward-compatible.
Features
- Creates associations for your models when application starts.
- Provides
Relation
&Role
models. - No configuration code needed.
- No code generated or inserted to your app (except migrations).
- Adds some useful methods to
ActiveRecord
objects to handle their relations.
Installation
- Add the gem to your
Gemfile
andbundle
it. - Copy migrations to your app (
rake rails_dynamic_associations:install:migrations
). - Migrate the DB (
rake db:migrate
).
Usage
Add configuration records to the DB:
Relation.create({
source_type: Person,
target_type: Book,
})
Or use a helper method:
Relation.seed Person, Book
Now you have:
person.books
book.people
Roles
You can create multiple role-based associations between two models.
Relation.seed Person, Book, %w[
author
editor
]
You will get:
person.books
person.authored_books
person.edited_books
book.people
book.author_people
book.editor_people
Special cases
In case you have set up relations with a User
model you'll get a slightly different naming:
Relation.seed User, Book, %w[
author
editor
]
book.users
book.authors
book.editors
The list of models to be handled this way can be set with actor_model_names
configuration parameter.
It includes User
by default.
TODO
- Describe self-referential associations.
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request