[英]elixir phoenix liveview - passing user id through socket
In liveview
, how can I pass the user data from leex
to the context
?在liveview
中,如何将用户数据从leex
传递到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.我有phx.gen.live
profiles
上下文,并且我想在每次用户创建新配置文件时将 user_id 添加到配置文件中。 I change the create_profile code to:我将 create_profile 代码更改为:
**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:我正在使用pow
,所以在正常的 phoenix 情况下,我会这样做:
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
.但在liveview
中,它使用的是socket
而不是conn
。 So I am not sure how to go about it.所以我不确定如何 go 关于它。
There are lots of different ways to do this but I will describe a straightforward approach.有很多不同的方法可以做到这一点,但我将描述一个简单的方法。
conn
.在您“登录”用户的 function 中,我假设您可以访问conn
。 I also assume you have a user_token
, if you are using Pow.如果您使用 Pow,我还假设您有一个user_token
。 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:现在 go 到你的live_helpers.ex
文件(或者如果你没有的话创建它)并像这样制作一个 function : 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:另外,在live_helpers
中,写这个 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:现在在您需要访问 current_user 的任何 LiveView 模块中,只需将其放入您的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
.然后您将可以访问session.assigns.current_user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.