【发布时间】: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
【问题讨论】: