【问题标题】:Adding Current User's Information to a Post in Phoenix Framework在 Phoenix 框架中将当前用户的信息添加到帖子中
【发布时间】:2016-07-17 01:26:30
【问题描述】:

我正在从 Rails 迁移到 Phoenix,遇到了一个我找不到答案的问题。

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

我还有一个 Post 模型/控制器/视图(为熟悉 Rails 的人准备的支架)。

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

在 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

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    您可以使用以下内容:

    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

    【讨论】:

    • 感谢加兹勒。我已经编辑了我的问题 - 我有一个私有函数来检查 conn.assigns.current_user (并且有效);但是,我收到一条错误消息,提示未定义函数 current_user。如何确保 current_user 在我的 conn.assigns 中?
    • 看起来你忘记了current_user = conn.assigns.current_user(我只在第一个例子中展示过。我已经更新了第二个例子)。如果你不想打电话给conn.assigns.current_user,那么你可能想看看hexdocs.pm/phoenix/Phoenix.Controller.htmloverriding :action部分
    • 是的 - 我做到了。说得通。感谢您的帮助!
    • 不能将conn.assigns.current_user 缩短为更短的名称并可以从应用程序中的任何位置访问吗?
    猜你喜欢
    • 2019-08-03
    • 2020-05-23
    • 2018-10-16
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多