Building Relationships

After the migration, Ecto generated a schema. This file is responsible for identifying the fields in a way that ties in to both the database table and the Elixir struct. Now let’s take a look at the schema in web/models/video.ex:

 schema ​"​​videos"​ ​do
  field ​:url​, ​:string
  field ​:title​, ​:string
  field ​:description​, ​:string
  belongs_to ​:user​, Rumbl.User
 
  timestamps
 end

Our schema sets up a belongs_to association, defining a :user_id field of type :integer and an association field. Our migration defines a :user_id foreign key. Ecto will use these elements to build the right association between our models.

The video module also includes a changeset ...

Get Programming Phoenix now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.