2016-12-07 42 views
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,這有助於解決這個問題,但我想知道如果有一個慣用的解決方案。

謝謝, 科裏

+0

「我目前得到一個錯誤」什麼錯誤? – Dogbert

+0

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> –

+0

在elixir ecto google羣組中詢問:https://groups.google.com/d/msg/elixir-ecto/s4heBr GN9J0/jwBFx3GBBAAJ –

回答

0

向錯誤:[角色:{ 「無效」,[式:{:陣列,:地圖}],例如:

列表有許多項,像:

schema "lists" do 

    field :name, :string 

    field :length, :integer 

    has_many :items, AnotherAgent.Item, on_delete: :delete_all 

def changeset(struct, params \\ %{}) do 
    struct 
    |> cast(params, [:name, :length]) 
    |> cast_assoc(:items, required: true) 
    |> validate_required([:name, :length]) 
end 

同在模板代碼,然後更新或創建的list_params,如:

%{"items" => %{"0" => %{"body" => "ten_list_item_0", "id" => "13"} }, "length" => "10", "name" => "ten"} 

我認爲在「sub_schema」中的字段將需要像這樣傳遞:

%{"index_str" => %{"field_one" => "value1", "field_two" => "value2"}}