Crecto
Search…
Associations
Crecto provides helper macros for defining associations between data models.

Has Many and Belongs To

1
class User < Crecto::Model
2
# schema...
3
4
has_many :images, Image
5
end
6
7
class Image < Crecto::Model
8
# schema...
9
10
belongs_to :user, User
11
end
Copied!

Has Many options

  • through - Specifying a join table
  • dependent: :destroy - On deletion, will delete all associated records first
  • dependent: :nullify - On deletion, will nullify all associated records foreign keys
  • foreign_key - Specify the foreign key field of of the associated table foreign_key: :user_id

Has One

1
class User < Crecto::Model
2
# schema...
3
4
has_one :address, Address
5
end
Copied!

Has One options

  • dependent: :destroy - On deletion, will delete all associated records first
  • dependent: :nullify - On deletion, will nullify all associated records foreign keys
  • foreign_key - Specify the foreign key field of of the associated table foreign_key: :user_id

Has Many Through / Join tables

1
class User < Crecto::Model
2
# schema...
3
4
has_many :memberships, Membership
5
has_many :groups, through: :memberships
6
end
7
8
class Group < Crecto::Model
9
# schema...
10
11
has_many :memberships, Membership
12
has_many :users, through: :memberships
13
end
14
15
class Membership < Crecto::Model
16
belongs_to :user, User
17
belongs_to :group, Group
18
end
Copied!

Setting associations

1
user = Repo.get!(User, 1)
2
image = Image.new
3
image.user = user
4
Repo.insert(image)
Copied!

Nil-check associations

If an association is not loaded, the normal accessor will raise an exception
1
user = Repo.get!(User, 1)
2
user.posts? # nil
3
user.posts # raises Crecto::AssociationNotLoaded
Copied!
For `has_many` preloads, the result will always be an array
1
user = Repo.get!(User, 1, Query.preload(:posts))
2
user.posts? # Array(Post)
3
user.posts # Array(Post)
Copied!
For belongs_to and has_one preloads, the result may still be nil if no record exists. If the association is nullable, always use the association_name? syntax.
1
post = Repo.get!(Post, 1, Query.preload(:user))
2
post.user? # nil
3
post.user # raises Crecto::AssociationNotLoaded
Copied!