In liveview
, how can I pass the user data from leex
to the context
? I have phx.gen.live
a profiles
context, and I want to add user_id to the profile every time user create the new profile. I change the create_profile code to:
**profiles.ex (context)**
def create_profile(attrs \\ %{}, userid) do
attrs = Map.put(attrs, "user_id", userid)
%Profile{}
|> Profile.changeset(attrs)
|> Repo.insert()
end
I am using pow
, so in normal phoenix case, I would just do this:
user = Pow.Plug.current_user(conn) #<-- this is conn
Profiles.create_profile(profile_params, user.id)
but in liveview
, instead of conn
, it use socket
. So I am not sure how to go about it.
There are lots of different ways to do this but I will describe a straightforward approach.
conn
. I also assume you have a user_token
, if you are using Pow. If so, do this:conn
|> put_session(:user_token, user_token)
live_helpers.ex
file (or create it if you don't have one) and make a function like this: def assign_defaults(session, socket) do
socket =
socket
|> assign_new(:current_user, fn ->
find_current_user(session)
end)
socket
end
live_helpers
, write this function: defp find_current_user(session) do
with user_token when not is_nil(user_token) <- session["user_token"],
%User{} = user <- Accounts.get_user_by_session_token(user_token),
do: user
end
mount
function: def mount(_params, session, socket) do
socket =
assign_defaults(session, socket)
{:ok, socket}
end
And then you will have access to the session.assigns.current_user
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.