Relationships
One to One
For one-to-one relationships, You can use the has_one and belongs_to in your models.
Note: one-to-one relationship does not support through associations yet.
class Team < Granite::Base
has_one :coach
column id : Int64, primary: true
column name : String
endThis will add a coach and coach= instance methods to the team which returns associated coach.
class Coach < Granite::Base
table coaches
belongs_to :team
column id : Int64, primary: true
column name : String
endThis will add a team and team= instance method to the coach.
For example:
In this example, you will need to add a team_id and index to your coaches table:
Foreign key is inferred from the class name of the Model which uses has_one. In above case team_id is assumed to be present in coaches table. In case its different you can specify one like this:
The class name inferred from the name but you can specify the class name:
One to Many
belongs_to and has_many macros provide a rails like mapping between Objects.
This will add a posts instance method to the user which returns an array of posts.
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