【问题标题】:many_to_many, checkboxes and cast_assocmany_to_many、复选框和 cast_assoc
【发布时间】:2017-03-16 17:02:07
【问题描述】:

我很好奇获取带有代表 many_to_many 关系的复选框以将关系保存在变更集中的表单结果的首选方法是什么?

这是一个例子: 架构:

  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

收到的参数:

%{email: "test@example.com", 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 我刚刚编辑了它以添加它,%{email: "test@example.com", name: "Cory", products: %{"1481122377646": %{_destroy: " 0", price: "13.00", title: "A product title"}}, roles: %{"1": "on"}} #Ecto.Changeset, title: "A product title"}, 错误: [],数据:#TestExAdmin.Product,有效?:true>]},错误:[角色:{“无效”,[类型:{:array,:map}]}],数据:#TestExAdmin.User , 有效吗?: false>
  • 在长生不老药谷歌群里提问:groups.google.com/d/msg/elixir-ecto/s4heBrGN9J0/jwBFx3GBBAAJ

标签: phoenix-framework ecto


【解决方案1】:

到报错:[roles: {"is invalid", [type: {:array, :map}],例如:

一个列表有很多项目,例如:

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"}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2011-05-15
    相关资源
    最近更新 更多