Build_assoc vs put_assoc

Context:

Here is my schema for my following entity:

schema "following" do
  field :name, :string
  field :avatar_url, :string
  field :screen_name, :string
  belongs_to :profile, Profile
  timestamps()
end

Here is my schema for profile entity:

schema "profile" do
field :name, :string
field :avatar_url, :string

has_many :following, Following,
  on_delete: :delete_all,
  foreign_key: :profile_id,
  on_replace: :nilify

timestamps()
end

Here is my code I used to link following to profile

def add_following_to_profile(%Profile{} = profile, %Following{} = following) do
   get_profile(profile.id)
   |> build_assoc(:following, following)
   |> Ecto.Changeset.change()
   |> Repo.update!()
 end

However here’s the result i’m getting when I run a test code

linked_following = Entity.add_following_to_profile(profile, following)
first_following = profile
                  |> Repo.preload(:following)
                  |> Map.get(:following)
                  |> List.first()

Log:

LINKED FOLLOWING: %Profilo.Entity.Lib.Following{
  __meta__: #Ecto.Schema.Metadata<:built, "following">,
  avatar_url: "https://avatars2.githubusercontent.com/u/577441?v=4",
  id: 374,
  inserted_at: ~N[2019-07-18 12:03:08],
  name: "Wes Bos",
  profile: #Ecto.Association.NotLoaded<association :profile is not loaded>,
  profile_id: 332,
  screen_name: "wesbos",
  updated_at: ~N[2019-07-18 12:03:08]
}

PROFILE: %Profilo.Entity.Lib.Profile{
  __meta__: #Ecto.Schema.Metadata<:loaded, "profile">,
  avatar_url: "https://profilo.app",
  following: [],
  id: 332,
  inserted_at: ~N[2019-07-18 12:03:08],
  name: "no profile",
  updated_at: ~N[2019-07-18 12:03:08]
}

Question:

  • For some reason when I print the profile that was linked to following, it doesn’t return any associated following. However, the following is able to recognize the linked profile_id though. Can some explain why this is case?

  • Also instead of using put_assoc to create associations can’t I use build_assoc and use ecto query to get followings that are associated with a specific profile id?

1 Like