Search code examples
phoenix-frameworkecto

The different between association belongs_to and add field id when define a schema?


What is the different when declare a relationship ?

schema "messages" do
    field :user_id, :id
end

and

schema "messages" do
    belongs_to :user, User
end

Solution

  • When you do field :user_id, :id, you're not actually declaring a relationship. You're just adding field called user_id with the type id.

    Belongs_to actually adds the relationship, with the default assumption that the foreign key is user_id. (This can be changed via the foreign_key opt).
    By using belongs_to, Ecto knows how to handle the related record when doing things like preloading, how to create/update with a related User attached, how to cascade the delete, etc.