Following on from my previous topic (How to display different UI if cookie exists or not in Phoenix LiveView) I found you could use put_session
in order to access the user’s ID in the mount/3 function.
I’m now wanting to expand on this I want to create an associated piece of content with that authenticated user. To expand on this a little further this is what my mount/3 function looks like…
@impl true
def mount(_params, %{"authenticated_user" => authenticated_user_id}, socket) do
{
:ok,
socket
|> assign(:clients, list_clients(authenticated_user_id))
}
end
My form template component thing looks like this,
<%= if @live_action in [:new, :edit] do %>
<%= live_modal @socket, AppWeb.ClientLive.FormComponent,
id: @client.id || :new,
title: @page_title,
action: @live_action,
client: @client,
return_to: Routes.client_index_path(@socket, :index) %>
<% end %>
and my handle_event/3
function looks something like this
def handle_event("save", %{"client" => client_params}, socket) do
save_client(socket, socket.assigns.action, client_params)
end
defp save_client(socket, :new, client_params) do
case Clients.create_client(client_params) do
{:ok, _client} ->
{:noreply,
socket
|> put_flash(:info, "Client created successfully")
|> push_redirect(to: socket.assigns.return_to)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
What would be the most effective way in order to create this new item associated with the signed in user? A couple of ideas I’ve already attempted are:
- In
handle_params/3
attempting to assign:client
with a pre-existing association e.g.%Client{user: ...}
but this didn’t work. - Passing
authenticated_user_id
as a parameter to the live_modal template, although I could get this working with enough force it just doesn’t seem right.
Really appreciate the help in advance Please let me know if you would like more information.