How to generate a form with inputs_for and a dynamic map field

I have a schema ie

defmodule Profile do
  use Ecto.Schema

  schema "profiles" do
    field :name, :string
    field :age, :integer
    field :type, :string
    field :settings, :map
  end
end

I’m trying to generate the form for this using inputs_for ie

<%= inputs_for f, :settings, fn f -> %>
# inputs
<% end %>

But it returns the error could not generate inputs for :settings from Profile. Check the field exists and it is one of embeds_one, embeds_many, has_one, has_many, belongs_to or many_to_many

I don’t want to use an embedded struct or a defined association because I want to have different settings values based on the type.

I can manually setting the name, value and id on the html input fields ie:

<%=
  checkbox f,
  :setting_example,
  name: "profile_params[settings][setting_example]",
  value: f.data.settings.setting_example
%>

to get around using inputs_for but it’s not ideal. Is there a way to do this?

Check out Polymorphic embed.

2 Likes