Now that we have our 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.
Most of the work for creating an Organization was in the model. In fact, there's almost nothing we have to change from the generator output in our OrganizationController, but we will need to make some significant changes to our tests.
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 create_user!/1 and create_user!/2 since we're adding 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.
defmodule PhoenixChat.OrganizationControllerTest do use PhoenixChat.ConnCase alias PhoenixChat.{Organization, Repo} @valid_attrs %{website: "http://www.foo.com", owner_id: 1} @invalid_attrs %{} test "lists all entries on index", %{conn: conn} do conn = get conn, organization_path(conn, :index) assert json_response(conn, 200)["data"] == [] end test "shows chosen resource", %{conn: conn} do create_user!(%{id: 1}) changeset = Organization.changeset(%Organization{}, @valid_attrs) org = Repo.insert!(changeset) conn = get conn, organization_path(conn, :show, org) response = json_response(conn, 200)["data"] assert %{"public_key" => _, "owner_id" => 1, "website" => "http://www.foo.com", "id" => _} = response end test "does not show resource instead throws error when id is nonexistent", %{conn: conn} do assert_error_sent 404, fn -> get conn, organization_path(conn, :show, -1) end end test "creates and renders resource when data is valid", %{conn: conn} do create_user!(%{id: 1}) conn = post conn, organization_path(conn, :create), organization: @valid_attrs assert json_response(conn, 201)["data"]["id"] assert Repo.get_by(Organization, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, organization_path(conn, :create), organization: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "updates and renders chosen resource when data is valid", %{conn: conn} do create_user!(%{id: 1}) changeset = Organization.changeset(%Organization{}, @valid_attrs) org = Repo.insert!(changeset) new_attrs = %{website: "http://www.bar.com"} conn = put conn, organization_path(conn, :update, org), organization: new_attrs assert json_response(conn, 200)["data"]["id"] assert Repo.get_by(Organization, new_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do create_user!(%{id: 1}) changeset = Organization.changeset(%Organization{}, @valid_attrs) org = Repo.insert!(changeset) conn = put conn, organization_path(conn, :update, org), organization: %{website: nil} assert json_response(conn, 422)["errors"] != %{} end test "deletes chosen resource", %{conn: conn} do create_user!(%{id: 1}) changeset = Organization.changeset(%Organization{}, @valid_attrs) org = Repo.insert!(changeset) conn = delete conn, organization_path(conn, :delete, org) assert response(conn, 204) refute Repo.get(Organization, org.id) endendNow when you run your tests, they should all pass.
The only thing we need to change in our controller is to add scrub_params/2 (docs), which simply checks to make sure the required parameters are there and turns all empty strings into nil. Everything else was created by the generator.
defmodule PhoenixChat.OrganizationController do use PhoenixChat.Web, :controller alias PhoenixChat.{Organization, Repo} plug :scrub_params, "organization" when action in [:create, :update] ...endWe'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 Ecto.Changeset.cast_assoc/2 in our User.registration_changeset/2, which will allow us to create and update the organization association at the same time we create our organization.
The first thing do is change our required fields in our 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 User as the association parameter. If we do, then we don't need to pass in an :owner_id since we will handle that in our cast_assoc/2 in our registration_changeset/2 and not in our changeset/2.
defmodule PhoenixChat.Organization do ... def changeset(struct, params \\ %{}, association \\ false) do required_fields = if association, do: [:website], else: [:website, :owner_id] struct |> cast(params, [:website, :owner_id]) |> validate_required(required_fields) |> update_change(:website, &set_uri_scheme/1) |> validate_change(:website, &validate_website/2) |> unique_constraint(:website) |> put_public_key() |> unique_constraint(:public_key) end @doc """ User for `cast_assoc/2` in `User.registration_changeset/2`. It's only difference from `changeset/3` is that it does not require an `owner_id`. """ def owner_changeset(struct, params \\ %{}) do changeset(struct, params, true) end ...endSo now within our User model, we need to update our registration_changeset/2 to handle the association mentioned above. This cast_assoc/2 will look for an :owned_organization field in the params and use that to assign an :owned_organization association between the user currently being created and a new organization.
... def registration_changeset(model, params) do model |> changeset(params) |> cast(params, ~w(password), []) |> cast_assoc(:owned_organization, with: &Organization.owner_changeset/2) |> validate_length(:password, min: 6, max: 100) |> put_encrypted_pw end...Note that our cast_assoc is looking for an :owned_organization key, so we will need to change the data we're sending on account creation to the following format:
{ username, email, password, owned_organization: { website }}Then for good housekeeping, let's write a couple tests for this change. For our Organization test, we are making sure that the new owner_changeset/2 works as expected.
... test "owner changeset does not require an owner id" do changeset = Organization.owner_changeset(%Organization{}, %{website: "foo.com"}) assert changeset.valid? end...Then within our User test, we are updating our registration_changeset/2 test to make sure that a new :owned_organization is created if it's provided.
... test "registration changeset with valid attributes" do valid_attrs = Map.put(@valid_attrs, :password, "password") changeset = User.registration_changeset(%User{}, valid_attrs) assert changeset.valid? assert get_change(changeset, :encrypted_password) # Test that a new owned_organization is created properly if it is provided valid_attrs = %{owned_organization: %{website: "http://www.foo.com"}} changeset = User.registration_changeset(changeset, valid_attrs) assert changeset.valid? assert get_change(changeset, :owned_organization).changes.website == "http://www.foo.com" assert get_change(changeset, :owned_organization).changes.public_key end...And that's it. Most of the boilerplate code for our CRUD endpoints was built by our generator. We barely had to change OrganizationController and we didn't have to touch our OrganizationView.