Theo Felippe
Theo Felippe

Reputation: 279

How to handle creation of nested records on phoenix/ecto?

Was wondering if anybody would be able to give me a hand with something i've been struggling with..

Long story short, i have a model "User" and another "Profile". Profile belongs_to User and User has_one Profile. All good so far..

When the user registers, I require email and password for the user model and first and last name that belong on the profile model. My question then is.. How do i handle inserting the user record with the profile in my RegistrationController?

Here's what the controller currently looks like (based on what I could gather from Jose's post on association and embeds -

def create(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{profile: %Profile{}}, user_params)
                |> Password.generate_password

    case Repo.insert(changeset) do
      {:ok, user} ->
        conn
        |> put_flash(:info, "You have successfully registered and logged in.")
        |> put_session(:current_user, user)
        |> redirect(to: page_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
end

Note: Passoword.generate_password does nothing but replace the password with a hashed one and return the changeset.

I have confirmed that the user_params indeed contain the profile information..

but this will raise an error something to do with...

...Assocs can only be manipulated via changesets, be it on insert, update or delete...

I've been struggling with this for a while and would be amazing if anyone could help :/

thanks in advance!

Upvotes: 0

Views: 492

Answers (1)

Theo Felippe
Theo Felippe

Reputation: 279

I've figured out.

changeset needed to be changed to:

changeset = User.changeset(%User{}, user_params)
            |> Password.generate_password

and voila! :)

Upvotes: 2

Related Questions