|
|
> Finally my database won't have those pointless join tables. This is one of my most-wanted features.
|
|
|
|
|
|
Has many connected through an array. PostgreSQL allows us to use arrays, Rails also allows us to use arrays, but why we have never been able to use them on associations. Well, honestly it was a bit hard to develop this feature, but the magic that it can do worth it. The idea is simple, one table stores all the ids and the other one says that `has many` records on that table because its records ids exist in the column of the array. Like: `Tag has many Videos connected through an array`. [PostgreSQL Docs](https://www.postgresql.org/docs/9.6/arrays.html)
|
|
|
|
|
|
# How it works
|
|
|
|
|
|
### Migration
|
|
|
|
|
|
A bit different than the usual `has_many`, the class that invokes it, doesn't hold the foreign key. Actually, the foreign table that stores the foreign keys.
|
|
|
|
|
|
```ruby
|
|
|
create_table "tag" do |t|
|
|
|
t.string "name"
|
|
|
end
|
|
|
|
|
|
# For this version 1.0.0, the references with array: true is not enabled
|
|
|
create_table "video" do |t|
|
|
|
t.bigint "tag_ids", array: true
|
|
|
t.string "title"
|
|
|
end
|
|
|
```
|
|
|
|
|
|
### Model
|
|
|
|
|
|
Now go to your model and simply activate the feature very similar to the old way, which just the extra `array: true` option.
|
|
|
|
|
|
```ruby
|
|
|
# models/tag.rb
|
|
|
class Tag < ApplicationRecord
|
|
|
has_many :videos, array: true
|
|
|
end
|
|
|
```
|
|
|
|
|
|
All the original features from the `has_many` association are available, preloading inclusive. You can check the methods on the [Associations Docs](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html) from Rails.
|
|
|
|
|
|
There's no extra or additional provided method, only some for metaprogramming if necessary. |
|
|
\ No newline at end of file |