And*_*yKo 5 elixir nested-forms ecto phoenix-framework
我正在处理复杂的注册表。我的用户将拥有他们的个人资料,其中包含联系信息和项目集合。我的架构(用户、个人资料、电话、集合、项目)如下所示:
defmodule MyProject.User
schema "users" do
field :email, :string
field :name, :string
has_many :profiles, MyProject.Profile, on_delete: :delete_all
has_many :collections, through: [:profiles, :collections]
timestamps()
end
end
defmodule MyProject.Profile
schema "profiles" do
field :address, :string
field :skype, :string
belongs_to :user, MyProject.User
has_many :phones, MyProject.Phone, on_delete: :delete_all
has_many :collections, MyProject.Collection, on_delete: :delete_all
timestamps()
end
end
defmodule MyProject.Phone
schema "phones" do
field :phone, :string
belongs_to :profile, MyProject.Profile
end
end
defmodule MyProject.Collection
schema "collections" do
field :name, :string
has_many :items, MyProject.Item, on_delete: :delete_all
timestamps()
end
end
defmodule MyProject.Item
schema "items" do
field :name, :string
field :type, :string
field :url, :string
belongs_to :collection, MyProject.Collection
timestamps()
end
end
Run Code Online (Sandbox Code Playgroud)
现在我需要构建复杂的注册表单,它允许创建用户和他的个人资料,其中包含一些手机和一个包含一些项目的集合,并提交一个表单。由于表注册不存在,我认为我需要为此使用embedded_schema,因为它与数据库表无关:
defmodule MyProject.Registration
embedded_schema do
end
end
Run Code Online (Sandbox Code Playgroud)
但我不确定如何描述其中的所有嵌套关联。我应该使用 has_one、has_many 还是 embed_one、embed_many 或两者都不使用,有什么影响?如何构建表单,我应该使用 input_for 嵌套关联吗?如何将所有关联值保存到数据库以保留所有关系?首先,需要保存用户,然后是他的个人资料,然后是一些电话,然后是收藏,最后是一些项目。所有这些都应该联系在一起。
我知道这个问题很古老,但它总是出现在我的搜索中。
不太令人满意,但最好的答案是,这取决于情况。embeds_one/embeds_many不会跟踪相同的记录,因为他们没有这个on_replace: :update选项。这意味着,如果您多次运行变更集(例如,每次用户添加新输入时在 LiveView 中),您的变更集将无法跟踪原始记录的内容。
因此,我建议使用has_one/has_many因为它更容易跟踪原始记录。
从那里我将考虑使用一个Multi操作从您获取特定数据embedded schema并将其转换为记录以保存到数据库中。
| 归档时间: |
|
| 查看次数: |
617 次 |
| 最近记录: |