Convention for params key name?

Hi y’all,

I’m trying to figure out the convention used for post params. In a controller, for example, you might have the following to pattern match incoming parameters.

def update(%{“user” => %{“name” => name, “email” => email}}) do …

My question: what is the convention for the key name for the posted parameters–in this case ‘user’?

I’ve searched google, the forums and the source code, but can’t find the answer. If anyone knows and can save me more searching, I owe you.

Rod

P.S. The form_for documentation says this:

:as - the name to be used in the form. Automatically inflected when a changeset is given.

Automatically inflected to what?

1 Like

The key comes from the changeset you supplied to the form_for call, or from the as: key in form_for if you use the conn parameter. This is described at https://hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html#functions but agree it doesn’t make it totally clear how that maps to the inbound parameters.

Basically the intent is similar to Rails (if thats a relevant observation for you). Input fields get named with an inflected name of the module used for the changeset, with the field name. So for example if the changeset is for a module User and the field you want to create for input is called email then you’ll get a form field with a name user[email]. In this case user will be a map key in the params, with sub-map that will have %{"email" => form_value, ...}.

2 Likes

Because those may map to fields in a struct, it should have the same convention as struct fields, which is snake_case. It is what we use in Elixir for atoms, variables, field names, etc.

2 Likes

I found my error:

In my tests, I had this:

conn = post conn, password_path(conn, :create), post: @valid_create_attrs

The last clause “post: @valid_create_attrs”, set the map key to ‘post’ while I was trying to match on ‘user’.

Fixed by this:

conn = post conn, password_path(conn, :create), user: @valid_create_attrs

Rod

2 Likes