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{} })
or
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!