has_many through

Has many through represents a relation where both side can relate to multiple models.

Basically, in SQL this can be performed by using a middle-table which store foreign key of both of the classes.

Usage Example

For example, let's assume we have a table posts and a table tags which are loosely connected: a post can have multiple tags at once, while a tag can references multiple posts. In this example, we will need a middle-table which will be named post_tags :

CREATE TABLE tags (
    id bigserial NOT NULL PRIMARY KEY, 
    name text NOT NULL
);

CREATE UNIQUE INDEX tags_name ON tags (name);

CREATE TABLE posts (
    id bigserial NOT NULL PRIMARY KEY,
    name text NOT NULL,
    content text
);

CREATE TABLE post_tags (
    tag_id bigint NOT NULL, 
    post_id bigint NOT NULL, 
    FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE, 
    FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE
);

You may notice usage of FOREIGN KEY constraints over post_tags. Clear doesn't provide any feature for cascading deletion, and relay exclusively on PostgreSQL.

Now, let's define our models:

And thats all ! Basically, in this case, we may not want to create a model PostTag as the table exists only to make the link between the two models.

Addition and deletion is provided in elegant way even without model:

p has to be saved in database before linking the tag.

Middle-table model

Optionally, we can define our middle-table model. In this case, you should use the model as through argument :

Note: The model Post::Tag don't have primary key which can lead to issues with Clear. Feel free to leave issues to the community here.

Last updated