Understanding belongs_to and has_one/many

I’m new to app development and have been playing around with Elixir/Ecto/Phoenix for a few weeks, and have finally reached a point where I am trying to make a demo app (using Phoenix) where I have associated models. Specifically I have a User model which has_one Profile (which belongs_to User), whose model I have just added. The user now only has an email address and a password, and the profile contains other data like name and dob and such. I want to be able now to enter all of this data in the registration form at the same time, and edit all of it at the same time.

I’m following a tutorial on nested forms to get the desired result, but I’m a little confused. Do I simply have to put

changeset = User.changeset(%User{ profile: %Profile{} })


changeset = User.changeset(%User{ profile: %Profile{} }, params_map)

in my (I guess always user) controller and a cast_assoc line in my user model and everything else (i.e. Repo functions) will just know what to do? If I want to make a change to the profile and user data at the same time, do I just need to do something like

user_map = Map.from_struct(Repo.get_by(User, id: user_id))
profile_map = Map.from_struct(Repo.get_by(Profile, user_id: user_id))
params = Map.merge(profile_map, user_map)
changeset = %User{ profile: %Profile{} }
|> User.changeset(params)

to build the parameters and changeset going forward (say for the :edit portion of my user controller)?

If so, awesome, and I sort of get that Ecto performs magical voodoo. If not, where is my understanding broken and is there a resource someone can point me toward for clarification? Thanks!

Did you read http://pages.plataformatec.com.br/ebook-whats-new-in-ecto-2-0? Iirc it contains a section about such a situation.

I wanted to throw a couple of links in here because I was trying to build nested forms in Phoenix with Ecto and this is the first place that I found in that attempt. Based on the link click number on @LostKobrakai’s reply, I think I’m not alone in that and so I wanted to give more options to those coming from Google.

Nested forms walkthrough: http://lesseverything.com/blog/nested-forms-in-phoenix/#
Blog post by José: http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/

The first one is easy to understand and helped me build what I needed to. The one by José seems to be more comprehensive and covers a lot of Ecto ground.