Associations

This section is based on Granite's README

One to Many

belongs_to and has_many macros provide a rails like mapping between Objects.

class User < Granite::ORM::Base
  adapter mysql

  has_many :posts

  field email : String
  field name : String
  timestamps
end

This will add a posts instance method to the user which returns an array of posts.

class Post < Granite::ORM::Base
  adapter mysql

  belongs_to :user

  field title : String
  timestamps
end

This will add a user and user= instance method to the post.

For example:

In this example, you will need to add a user_id and index to your posts table:

Many to Many

Instead of using a hidden many-to-many table, Granite recommends always creating a model for your join tables. For example, let's say you have many users that belong to many rooms. We recommend adding a new model called participants to represent the many-to-many relationship.

Then you can use the belongs_to and has_many relationships going both ways.

The Participant class represents the many-to-many relationship between the Users and Rooms.

Here is what the database table would look like:

has_many through:

As a convenience, we provide a through: clause to simplify accessing the many-to-many relationship:

This will allow you to find all the rooms that a user is in:

And the reverse, all the users in a room:

Last updated