0
我很好奇什麼是最好的方式來獲取表單的結果與複選框代表一個many_to_many關係來保存變更集中的關係?many_to_many,複選框和cast_assoc
下面是一個例子: 模式:
schema "users" do
field :name, :string
field :email, :string
field :active, :boolean, default: true
has_many :products, TestExAdmin.Product
has_many :noids, TestExAdmin.Noid
many_to_many :roles, TestExAdmin.Role, join_through: TestExAdmin.UserRole
end
複選框:
<div class="form-group">
<label class="col-sm-2 control-label" for="user_roles">Roles</label>
<div class="col-sm-10">
<input name="user[roles][]" type="hidden" value="">
<div class="checkbox"><label><input type="checkbox" name="user[roles][1]">role1</label></div>
</div>
</div>
變更:接收
def changeset(model, params \\ %{}) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_assoc(:noids, required: false)
|> cast_assoc(:products, required: false)
|> cast_assoc(:roles, required: false)
end
PARAMS:
%{email: "[email protected]", name: "Cory",
products: %{"1481120458618": %{_destroy: "0", price: "13.00",
title: "A product title"}}, roles: %{"1": "on"}}
目前,我得到一個錯誤:
errors: [roles: {"is invalid", [type: {:array, :map}]
我發現這個插件,https://github.com/adam12/phoenix_mtm,這有助於解決這個問題,但我想知道如果有一個慣用的解決方案。
謝謝, 科裏
「我目前得到一個錯誤」什麼錯誤? – Dogbert
Thanks @Dogbert我剛編輯它添加它,%{email:「[email protected]」,名稱:「Cory」, products:%{「1481122377646」:%{_ destroy:「0」,price:「 「}, title:」A product title「}},roles:%{」1「:」on「}} #Ecto.Changeset,title:」A product title「},errors:[], data: #TestExAdmin.Product <>,valid?:true>]}, 錯誤:[roles:{「is invalid」,[type:{:array,:map}]}], data:#TestExAdmin.User < ,valid ?: false> –
在elixir ecto google羣組中詢問:https://groups.google.com/d/msg/elixir-ecto/s4heBr GN9J0/jwBFx3GBBAAJ –