我有兩個機型的用戶和地址嵌入的關聯,我連他們是這樣的:外生過濾空記錄
defmodule App.Address do
# ...
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:address, :city])
end
end
當我使用:
inputs_for :addresses, [append: [App.Address{}]], fn address ->
text_input address, :address, class: ""
end
,我進入空的數據,它被保存爲零,我希望有一個解決方案,以過濾掉空的數據,並防止他們得到保存,所有我想出的是在控制器使用Enum.filter這將得到醜陋,因爲我認爲:
...
filtered_addresses = Enum.filter(user_params["addresses"], fn {x, map} ->
map.address != "" and map.city != ""
end)
user_params = Map.put(user_params, :addresses, filtered_addresses)
是否有更清潔的方式使用模型驗證,或在控制器中更乾淨的方式?
我覺得函數[cast_embed/3](https://hexdocs.pm/ecto/Ecto.Changeset.html#cast_embed/3)應該接受一個類似':reject_if'的選項,類似於rails [accep_nested_attributes_for]( http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)。我發佈了[問題到elixir-ecto郵件列表](https://groups.google.com/forum/#!topic/elixir-ecto/ScPo16tfllc) –
@OleksandrAvoyants這是':with'選項的要點。您指定一個變更集,如果它無效,可以拒絕它。 –
@JustinWood請糾正我,如果我錯了,但我認爲目前沒有辦法改變集拒絕記錄。 –