Clear ORM
Search…
has_many
Has many represents one of the counter part of belongs to relation. It assumes the current model is referenced by a collection of another model.
Let's see the example used in the chapter belongs_to:
1
CREATE TABLE categories (
2
id bigserial NOT NULL PRIMARY KEY,
3
name text NOT NULL
4
)
5
6
CREATE TABLE posts (
7
id bigserial NOT NULL PRIMARY KEY,
8
name text NOT NULL,
9
content text,
10
category_id bigint NOT NULL
11
)
Copied!
1
class Post
2
include Clear::Model
3
4
primary_key
5
6
column name : String
7
column content : String?
8
9
belongs_to category : Category
10
end
11
12
class Category
13
include Clear::Model
14
15
primary_key
16
17
column name : String
18
19
has_many posts : Post
20
end
Copied!
Here, we said a category has many posts. The posts can be accessed through the method posts which return a Collection:
1
c = Category.query.find!{name == "Technology"} # Retrieve the category named Technology
2
3
c.posts.each do |post|
4
puts "Post name: #{post.name}"
5
end
Copied!
Note: The relation can be refined after fetching:
1
# Fetch only the posts which starts by a digit:
2
c.posts.where{name =~ /^[0-9]/i}.each do |post|
3
puts "Post name: #{post.name}"
4
end
Copied!

Customizing the relation

Clear uses naming convention to infer the name of the foreign key. You may want to override this behavior by adding some parameters:
1
has_many relation_name : RelationType,
2
foreign_key: "column_name", own_key: "column_name", no_cache: true|false
Copied!
Argument
Description
Default value
foreign_key
The foreign key which is inside the relative model
[underscore_model_name]_id
own_key
The key against what the relation is tested, primary key by default
self.class.__pkey__
no_cache
Never cache the relation (note: planned feature)
false

Adding to relation

An object can be added into the relation collection using << operator:
1
c.posts << Post.new({name: "A good post"})
Copied!
In this case, the post is saved during the add operation.
Last modified 10mo ago