将当前用户的信息添加到Phoenix Framework中的帖子

And*_*rie 5 elixir phoenix-framework

我正在从Rails搬到菲尼克斯,然后遇到一个我无法找到答案的问题.

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

我还有一个Post模型/控制器/视图(熟悉w Rails的脚手架).

我希望在提交表单(每个帖子将属于用户)时使用@current_user ID自动填充Post字段,而不包含用户必须填写的表单字段.

在Rails中,这非常简单......像这样添加到帖子控制器的创建动作中:

@post.user = current_user.id
Run Code Online (Sandbox Code Playgroud)

如何使用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
Run Code Online (Sandbox Code Playgroud)

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

解决方案(感谢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
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 10

您可以使用以下内容:

current_user = conn.assigns.current_user
changeset = Post.changeset(%Post{user_id: current_user.id}, post_params)
Run Code Online (Sandbox Code Playgroud)

或者使用Ecto.build_assoc/3:

current_user = conn.assigns.current_user
changeset = Ecto.build_assoc(current_user, :posts, post_params)
Run Code Online (Sandbox Code Playgroud)

这里假设你有current_user你的conn.assigns.