{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/crud-endpoints-for-organization-part-1","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"CRUD Endpoints for Organization: Part 1\",\n  \"order\": 43,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"CRUD Endpoints for Organization: Part 1\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Update OrganizationControllerTest\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Update OrganizationController\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Create organization on signup\")), mdx(\"p\", null, \"Now that we have our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" ready, we need to give our frontend the ability to add and update them. We're going to do this by adding some simple CRUD (Create Read Update Delete) operations.\"), mdx(\"h2\", null, \"Update OrganizationControllerTest\"), mdx(\"p\", null, \"Most of the work for creating an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" was in the model. In fact, there's almost nothing we have to change from the generator output in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"OrganizationController\"), \", but we will need to make some significant changes to our tests.\"), mdx(\"p\", null, \"This is a big block of code, but none of this is new--we covered each of these tests in the previous section on testing controllers. One thing to note is that we can call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user!/1\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user!/2\"), \" since we're adding \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"use PhoenixChat.ConnCase\"), \" to our module. You should go through each test to make sure you understand what it's testing. If you run into issues, refer back to the chapter on testing controllers.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.OrganizationControllerTest do\\n  use PhoenixChat.ConnCase\\n\\n  alias PhoenixChat.{Organization, Repo}\\n  @valid_attrs %{website: \\\"http://www.foo.com\\\", owner_id: 1}\\n  @invalid_attrs %{}\\n\\n  test \\\"lists all entries on index\\\", %{conn: conn} do\\n    conn = get conn, organization_path(conn, :index)\\n    assert json_response(conn, 200)[\\\"data\\\"] == []\\n  end\\n\\n  test \\\"shows chosen resource\\\", %{conn: conn} do\\n    create_user!(%{id: 1})\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n    org = Repo.insert!(changeset)\\n\\n    conn = get conn, organization_path(conn, :show, org)\\n    response = json_response(conn, 200)[\\\"data\\\"]\\n    assert %{\\\"public_key\\\" => _, \\\"owner_id\\\" => 1, \\\"website\\\" => \\\"http://www.foo.com\\\",\\n      \\\"id\\\" => _} = response\\n  end\\n\\n  test \\\"does not show resource instead throws error when id is nonexistent\\\", %{conn: conn} do\\n    assert_error_sent 404, fn ->\\n      get conn, organization_path(conn, :show, -1)\\n    end\\n  end\\n\\n  test \\\"creates and renders resource when data is valid\\\", %{conn: conn} do\\n    create_user!(%{id: 1})\\n    conn = post conn, organization_path(conn, :create), organization: @valid_attrs\\n\\n    assert json_response(conn, 201)[\\\"data\\\"][\\\"id\\\"]\\n    assert Repo.get_by(Organization, @valid_attrs)\\n  end\\n\\n  test \\\"does not create resource and renders errors when data is invalid\\\", %{conn: conn} do\\n    conn = post conn, organization_path(conn, :create), organization: @invalid_attrs\\n    assert json_response(conn, 422)[\\\"errors\\\"] != %{}\\n  end\\n\\n  test \\\"updates and renders chosen resource when data is valid\\\", %{conn: conn} do\\n    create_user!(%{id: 1})\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n    org = Repo.insert!(changeset)\\n\\n    new_attrs = %{website: \\\"http://www.bar.com\\\"}\\n    conn = put conn, organization_path(conn, :update, org), organization: new_attrs\\n\\n    assert json_response(conn, 200)[\\\"data\\\"][\\\"id\\\"]\\n    assert Repo.get_by(Organization, new_attrs)\\n  end\\n\\n  test \\\"does not update chosen resource and renders errors when data is invalid\\\", %{conn: conn} do\\n    create_user!(%{id: 1})\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n    org  = Repo.insert!(changeset)\\n    conn = put conn, organization_path(conn, :update, org), organization: %{website: nil}\\n\\n    assert json_response(conn, 422)[\\\"errors\\\"] != %{}\\n  end\\n\\n  test \\\"deletes chosen resource\\\", %{conn: conn} do\\n    create_user!(%{id: 1})\\n    changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n    org  = Repo.insert!(changeset)\\n    conn = delete conn, organization_path(conn, :delete, org)\\n\\n    assert response(conn, 204)\\n    refute Repo.get(Organization, org.id)\\n  end\\nend\\n\")), mdx(\"p\", null, \"Now when you run your tests, they should all pass.\"), mdx(\"h2\", null, \"Update OrganizationController\"), mdx(\"p\", null, \"The only thing we need to change in our controller is to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"scrub_params/2\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.Controller.html#scrub_params/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \", which simply checks to make sure the required parameters are there and turns all empty strings into \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \". Everything else was created by the generator.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.OrganizationController do\\n  use PhoenixChat.Web, :controller\\n\\n  alias PhoenixChat.{Organization, Repo}\\n\\n  plug :scrub_params, \\\"organization\\\" when action in [:create, :update]\\n\\n  ...\\n\\nend\\n\")), mdx(\"h2\", null, \"Create organization on signup\"), mdx(\"p\", null, \"We'll also want to give our user the ability to create an organization at the same time they create their account. To accomplish this, we're going to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Ecto.Changeset.cast_assoc/2\"), \" in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User.registration_changeset/2\"), \", which will allow us to create and update the organization association at the same time we create our organization.\"), mdx(\"p\", null, \"The first thing do is change our required fields in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \". Since we are allowing an organization to be created at the same time as a user, we may want to pass a newly-created \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" as the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"association\"), \" parameter. If we do, then we don't need to pass in an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owner_id\"), \" since we will handle that in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"cast_assoc/2\"), \" in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" and not in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Organization do\\n  ...\\n\\n  def changeset(struct, params \\\\\\\\ %{}, association \\\\\\\\ false) do\\n    required_fields = if association, do: [:website], else: [:website, :owner_id]\\n\\n    struct\\n    |> cast(params, [:website, :owner_id])\\n    |> validate_required(required_fields)\\n    |> update_change(:website, &set_uri_scheme/1)\\n    |> validate_change(:website, &validate_website/2)\\n    |> unique_constraint(:website)\\n    |> put_public_key()\\n    |> unique_constraint(:public_key)\\n  end\\n\\n  @doc \\\"\\\"\\\"\\n  User for `cast_assoc/2` in `User.registration_changeset/2`. It's only difference\\n  from `changeset/3` is that it does not require an `owner_id`.\\n  \\\"\\\"\\\"\\n  def owner_changeset(struct, params \\\\\\\\ %{}) do\\n    changeset(struct, params, true)\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"So now within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model, we need to update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" to handle the association mentioned above. This \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"cast_assoc/2\"), \" will look for an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \" field in the params and use that to assign an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \" association between the user currently being created and a new organization.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  def registration_changeset(model, params) do\\n    model\\n    |> changeset(params)\\n    |> cast(params, ~w(password), [])\\n    |> cast_assoc(:owned_organization, with: &Organization.owner_changeset/2)\\n    |> validate_length(:password, min: 6, max: 100)\\n    |> put_encrypted_pw\\n  end\\n...\\n\")), mdx(\"p\", null, \"Note that our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"cast_assoc\"), \" is looking for an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \" key, so we will need to change the data we're sending on account creation to the following format:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"{\\n  username,\\n  email,\\n  password,\\n  owned_organization: {\\n    website\\n  }\\n}\\n\")), mdx(\"p\", null, \"Then for good housekeeping, let's write a couple tests for this change. For our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" test, we are making sure that the new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owner_changeset/2\"), \" works as expected.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  test \\\"owner changeset does not require an owner id\\\" do\\n    changeset = Organization.owner_changeset(%Organization{}, %{website: \\\"foo.com\\\"})\\n    assert changeset.valid?\\n  end\\n...\\n\")), mdx(\"p\", null, \"Then within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" test, we are updating our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset/2\"), \" test to make sure that a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \" is created if it's provided.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  test \\\"registration changeset with valid attributes\\\" do\\n    valid_attrs = Map.put(@valid_attrs, :password, \\\"password\\\")\\n    changeset = User.registration_changeset(%User{}, valid_attrs)\\n    assert changeset.valid?\\n    assert get_change(changeset, :encrypted_password)\\n\\n    # Test that a new owned_organization is created properly if it is provided\\n    valid_attrs = %{owned_organization: %{website: \\\"http://www.foo.com\\\"}}\\n    changeset = User.registration_changeset(changeset, valid_attrs)\\n    assert changeset.valid?\\n    assert get_change(changeset, :owned_organization).changes.website == \\\"http://www.foo.com\\\"\\n    assert get_change(changeset, :owned_organization).changes.public_key\\n  end\\n...\\n\")), mdx(\"p\", null, \"And that's it. Most of the boilerplate code for our CRUD endpoints was built by our generator. We barely had to change \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"OrganizationController\"), \" and we didn't have to touch our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"OrganizationView\"), \".\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"CRUD Endpoints for Organization: Part 1 Update OrganizationControllerTest Update OrganizationController Create organization on signup Now…","frontmatter":{"title":"CRUD Endpoints for Organization: Part 1","order":43,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"crud-endpoints-for-organization-part-1","prevNode":{"frontmatter":{"title":"Creating an Organization Model","active":true,"free":false,"order":41,"tech":["phoenix"]},"fields":{"slug":"creating-an-organization-model"}},"nextNode":{"frontmatter":{"title":"Controlling and Validating Forms","active":true,"free":false,"order":44,"tech":["react"]},"fields":{"slug":"controlling-and-validating-forms"}}}},"staticQueryHashes":["1723017916"]}