【发布时间】:2021-01-02 06:50:35
【问题描述】:
我对 elixir/phoenix 很陌生,而且我在一个概念上有点挣扎。我找到了解决方法,但我对此并不满意。
上下文: 我在我的数据库中创建了一个“项目”。现在我想通过项目“显示”页面创建一个与项目相关的“工作项”。由于它与该特定项目相关,因此我需要将 ID 添加到变更集。
我尝试在projects_controller 中这样做:
def show(conn, %{"id" => id}) do
project = Clients.get_project!(id)
changeset = Clients.change_work_item(%BudgetItem{project_id: project.id})
render(conn, "show.html", project: project, changeset: changeset)
end
这是表格:
%= form_for @changeset, @action, fn f -> %>
<%= if @changeset.action do %>
<div class="alert alert-danger">
<p>Oops, something went wrong! Please check the errors below.</p>
</div>
<% end %>
<%= label f, :title %>
<%= text_input f, :title %>
<%= error_tag f, :title %>
<%= label f, "duration" %>
<%= number_input f, :amount_in_cents %>
<%= error_tag f, :amount_in_cents %>
<div>
<%= submit "Save" %>
</div>
<% end %>
当我点击提交时,project_id 不在我的 work_item_controller 中的变更集中 - 我的理解是这是因为 elixir 中数据的不变性。我的解决方法是现在我在“存储”project_id (<%= hidden_input f, :project_id %>) 的视图中有一个隐藏字段。这行得通,但我对此不满意,因为用户可以干预它并且很好 - “滥用”视图来执行此操作感觉是错误的。你们中的任何人都可以向我解释这通常是如何完成的吗?我一直找不到令人满意的解决方案。
如果您需要更多代码来更好地理解实现,请告诉我。
感谢您的宝贵时间!
编辑:
defmodule SthWeb.WorkItemController do
use SthWeb, :controller
alias Sth.Clients
alias Sth.Clients.Project
def create(conn, %{"work_item" => work_item_params}) do
case Clients.create_work_item(work_item_params) do
{:ok, work_item} ->
conn
|> put_flash(:info, "Budget increased successfully!")
|> redirect(to: Routes.project_path(conn, :show, work_item.project_id))
{:error, changeset} ->
conn
|> put_flash(:info, "Something went wrong.")
|> redirect(to: Routes.project_path(conn, :show, 1))
end
end
end
【问题讨论】:
标签: elixir phoenix-framework ecto