在 Phoenix Framework 中将当前用户的信息添加到 Post

Adding Current User's Information to a Post in Phoenix Framework

我正从 Rails 转到 Phoenix,运行 遇到了一个我找不到答案的问题。

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

我也有一个Postmodel/controller/view(脚手架给熟悉的wRails)

我想在提交表单时自动用@current_user ID 填充一个Post 字段(每个post 将属于一个用户)没有表单字段用户必须填写。

在 Rails 中,这非常简单...添加到 post 控制器工作的创建操作中的类似内容:

@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

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

解决方案(感谢 Gazler):

  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)

这假设您的 conn.assigns 中有 current_user