JSON and Ecto not working well in regards to cast_assoc

I was hoping to get an opinion in regards to getting data from the frontend. I’m currently using Axios to do a post request to my /api/users. The problem I’m running into is once I hit the backend. I have a User model and a Credential Model. It has a cast_assoc as |> cast_assoc(:credential, with: &Credential.changeset/2, required: true) and considered to be valid?:false when I pass data. The question I have is in regards to how we send data to the backend.

Currently, I’m seeing my data appearing as %{"email" => "sdsds", "password" => "sdsds", "username" => "sdsd"} which will past the User casting but fail on credential since it’s looking for a credential key. Is there a different approach one should take or would I need to set a key of credentials from the frontend pointing to the properties it needs to past the casting?

Thanks for all the advise and clarity in regards to best practice when dealing with JSON and cast_assoc.

Error => 
{:error,
 #Ecto.Changeset<
   action: :insert,
   changes: %{username: "sdsd"},
   errors: [credential: {"can't be blank", [validation: :required]}],
   data: #SafeMe.Accounts.User<>,
   valid?: false
 >}
%{
  "credentials": %{"email" => "sdsds", "password" => "sdsds"}, 
  "username" => "sdsd"
}

This is what you’d ned to send to the backend if you want cast_assoc to be able to pick up the values. But you can also transform the data send from the frondend in e.g. the controller before passing it on to your business logic.

2 Likes