Simon Cooper
Simon Cooper

Reputation: 1594

expected params to be a map error when trying to submit form in Phoenix 1.3

I have a contact form, using the below changeset.

def changeset(%Email{} = email, attrs) do

    email
    |> cast(attrs, [:name, :email, :message, :event])
    |> validate_required([:name, :email, :message])
  end

But I get the following error when I try to submit the form:

expected params to be a map, got: `#Ecto.Changeset<action: nil, changes: %
{email: "[email protected]", event: "wedding", message: "hello", name: "Simon"}, 
errors: [], data: #Iotc.Contact.Email<>, valid?: true>`

my create function is:

  def create(conn, %{"email" => email_params}) do
    changeset = Contact.Email.changeset(%Iotc.Contact.Email{}, email_params)
    case Contact.create_email(changeset) do
      {:ok, email} ->
        conn
        |> put_flash(:info, "Email sent")
        |> redirect(to: email_path(conn, :index))
      {:error, changeset} ->
        conn
        |> put_flash(:error, "Something went wrong")
        |> render("index.html", changeset: changeset)
    end
  end

I'm assuming it's not picking up the attrs?

And from contact.ex:

  def create_email(attrs \\ %{}) do
    %Email{}
    |> Email.changeset(attrs)
    |> Repo.insert()
  end

Upvotes: 2

Views: 3554

Answers (1)

Dogbert
Dogbert

Reputation: 222328

Contact.create_email/1 expects a map of attrs (not a changeset) and calls Contact.Email.changeset/2 itself, so you need to pass email_params to it:

def create(conn, %{"email" => email_params}) do
  case Contact.create_email(email_params) do
    ...
  end
end

Upvotes: 2

Related Questions