gpt4 book ai didi

elixir - 将当前用户的信息添加到 Phoenix 框架中的帖子中

转载 作者:行者123 更新时间:2023-12-04 17:17:07 24 4
gpt4 key购买 nike

我正在从 Rails 搬到 Phoenix 并遇到一个我找不到答案的问题。

我已经设置了用户身份验证(通过在私有(private)身份验证函数中检查@current_user)。

我还有一个 Post 模型/ Controller / View (为熟悉 w Rails 的人准备的脚手架)。

我想在提交表单时使用@current_user ID 自动填充一个 Post 字段(每个帖子都属于一个用户),而没有用户必须填写的表单字段。

在 Rails 中,这非常简单......像这样添加到后 Controller 的创建操作中的东西可以工作:

@post.user = current_user.id

我如何使用 Phoenix Framework/Elixir 做到这一点?

这是我的 PostController 中的创建操作
  def create(conn, %{"post" => post_params}) do
changeset = Post.changeset(%Post{}, post_params)

case Repo.insert(changeset) do
{:ok, _project} ->
conn
|> put_flash(:info, "Please check your email inbox.")
|> redirect(to: page_path(conn, :thanks))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end

这种类型的逻辑应该在 Controller 还是模型中执行?或者是否有一种在 View 中执行此操作的好方法(不使用不安全的隐藏字段)。

解决方案 (感谢加兹勒):
  def create(conn, %{"post" => post_params}) do
current_user = conn.assigns.current_user
changeset = Post.changeset(%Post{user_id = current_user.id}, post_params)
case Repo.insert(changeset) do
{:ok, _project} ->
conn
|> put_flash(:info, "Please check your email inbox.")
|> redirect(to: page_path(conn, :thanks))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end

最佳答案

您可以使用以下内容:

current_user = conn.assigns.current_user
changeset = Post.changeset(%Post{user_id: current_user.id}, post_params)

或使用 Ecto.build_assoc/3 :
current_user = conn.assigns.current_user
changeset = Ecto.build_assoc(current_user, :posts, post_params)

这假设您有 current_user在您的 conn.assigns .

关于elixir - 将当前用户的信息添加到 Phoenix 框架中的帖子中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com