如何在Phoenix框架中处理关联和嵌套形式? [英] How to handle associations and nested forms in Phoenix framework?
本文介绍了如何在Phoenix框架中处理关联和嵌套形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Phoenix框架中处理关联和嵌套表单的方式是什么?如何创建具有嵌套属性的表单?一个人将如何在控制器和模型中处理它?
What is the way to handle associations and nested forms in Phoenix framework? How would one create a form with nested attributes? How would one handle it in the controller and model?
推荐答案
有一个处理1-1情况的简单示例.
There is a simple example of handling 1-1 situation.
想象一下,我们有一个Car
和Engine
模型,显然还有一个Car
has_one Engine
.所以有汽车模型的代码
Imagine we have a Car
and an Engine
models and obviously a Car
has_one Engine
. So there's code for the car model
defmodule MyApp.Car do
use MyApp.Web, :model
schema "cars" do
field :name, :string
has_one :engine, MyApp.Engine
timestamps
end
def changeset(model, params \\ :empty) do
model
|> cast(params, ~w(name), ~w())
|> validate_length(:name, min: 5, message: "No way it's that short")
end
end
和引擎型号
defmodule MyApp.Engine do
use MyApp.Web, :model
schema "engines" do
field :type, :string
belongs_to :car, MyApp.Car
timestamps
end
def changeset(model, params \\ :empty) do
model
|> cast(params, ~w(type), ~w())
|> validate_length(:type, max: 10, message: "No way it's that long")
end
end
表单的简单模板->
<%= form_for @changeset, cars_path(@conn, :create), fn c -> %>
<%= text_input c, :name %>
<%= inputs_for c, :engine, fn e -> %>
<%= text_input e, :type %>
<% end %>
<button name="button" type="submit">Create</button>
<% end %>
和控制器->
defmodule MyApp.CarController do
use MyApp.Web, :controller
alias MyApp.Car
alias MyApp.Engine
plug :scrub_params, "car" when action in [:create]
def new(conn, _params) do
changeset = Car.changeset(%Car{engine: %Engine{}})
render conn, "new.html", changeset: changeset
end
def create(conn, %{"car" => car_params}) do
engine_changeset = Engine.changeset(%Engine{}, car_params["engine"])
car_changeset = Car.changeset(%Car{engine: engine_changeset}, car_params)
if car_changeset.valid? do
Repo.transaction fn ->
car = Repo.insert!(car_changeset)
engine = Ecto.Model.build(car, :engine)
Repo.insert!(engine)
end
redirect conn, to: main_page_path(conn, :index)
else
render conn, "new.html", changeset: car_changeset
end
end
end
and an interesting blog post on the subject that can clarify some things as well -> here
这篇关于如何在Phoenix框架中处理关联和嵌套形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文