{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/associate-organizations-and-users","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\": \"Associate Organizations and Users\",\n  \"order\": 41,\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, \"Associate Organizations and Users\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Alter :users table\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Update models\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Update model tests\")), mdx(\"p\", null, \"Now that we have organizations set up, we need to associate our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model with an organization. A user may create an organization and a user will be associated with an organization. The owner of the organization will have special priveleges that we will add later on (such as inviting others, deleting the organization, etc).\"), mdx(\"h2\", null, \"Alter :users table\"), mdx(\"p\", null, \"The first and most straightforward thing to do is to generate a new migration and alter the existing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":users\"), \" table to include a new field for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":organization_id\"), \" so we know to which organization this user belongs.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.gen.migration add_organization_reference_in_user\\n\")), mdx(\"p\", null, \"Then we alter the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":users\"), \" table and add an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":organization_id\"), \" which references our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":organizations\"), \" table. We're also setting an option to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nilify_all\"), \" so when a user is deleted, all of the user's owned organizations will have their \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owner_id\"), \" set to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \". We do this since we want users whose organizations have been deleted to have a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \" value rather than continue to reference a non-existent user.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"\\ndefmodule PhoenixChat.Repo.Migrations.AddOrganizationReferenceInUser do\\n  use Ecto.Migration\\n\\n  def change do\\n    alter table(:users) do\\n      add :organization_id, references(:organizations, on_delete: :nilify_all)\\n    end\\n  end\\nend\\n\\n\")), mdx(\"p\", null, \"Now we need to update our models to reflect this change.\"), mdx(\"h2\", null, \"Update User and Organization models\"), mdx(\"p\", null, \"The first change we'll make is to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model, in which we will add an association between our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model and our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" model. In this case, we're adding a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"has_one\"), \" association between the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" and the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \", signifying that each user may only own one organization. Then we're adding a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"belongs_to\"), \" association to link our users to a particular organization.\"), mdx(\"p\", null, \"For a more detailed explanation of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"belongs_to/3\"), \" function, here's one from the \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3\",\n    \"parentName\": \"p\"\n  }, \"Ecto docs\"), \".\"), mdx(\"blockquote\", null, mdx(\"p\", {\n    \"parentName\": \"blockquote\"\n  }, \"You should use belongs_to in the table that contains the foreign key. Imagine a company to manager relationship. If the company contains the manager_id in the underlying database table, we say the company belongs to manager.\")), mdx(\"p\", null, \"We're also going to associate our organizations with our users.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.User do\\n  use PhoenixChat.Web, :model\\n  alias PhoenixChat.Organization\\n\\n  schema \\\"users\\\" do\\n    field :email, :string\\n    field :encrypted_password, :string\\n    field :username, :string\\n    field :password, :string, virtual: true\\n\\n    has_one :owned_organization, Organization, foreign_key: :owner_id\\n    belongs_to :organization, Organization\\n\\n    timestamps\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Then within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" model, we add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"has_many\"), \" association with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":admins\"), \" with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":organization_id\"), \" as the foreign key, telling our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" schema that it should expect to have (potentially) many admins. We also say that an organization \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"belongs_to\"), \" whichever \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" is the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owner_id\"), \" foreign key that we set above in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model.\"), mdx(\"p\", null, \"We're also going to adjust our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" to require an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owner_id\"), \" when an organization is created because we don't want organizations without an owner.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Organization do\\n  use PhoenixChat.Web, :model\\n  alias PhoenixChat.{User, Repo}\\n\\n  schema \\\"organizations\\\" do\\n    field :public_key, :string\\n    field :website, :string\\n\\n    has_many  :admins, User, foreign_key: :organization_id\\n    belongs_to :owner, User, foreign_key: :owner_id\\n\\n    timestamps()\\n  end\\n\\n  @doc \\\"\\\"\\\"\\n  Builds a changeset based on the `struct` and `params`.\\n  \\\"\\\"\\\"\\n  def changeset(struct, params \\\\\\\\ %{}) do\\n    struct\\n    |> cast(params, [:website, :owner_id])\\n    |> validate_required([:website, :owner_id])\\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  ...\\nend\\n\")), mdx(\"p\", null, \"The last thing we should do before proceeding is update our model tests with these new associations.\"), mdx(\"h2\", null, \"Update model tests\"), mdx(\"p\", null, \"We'll start with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" tests because they're simpler.\"), mdx(\"p\", null, \"Our first test checks to make sure that we can create an organization with an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owner_id\"), \" that references a user. In order to do this, we need to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.preload/3\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Repo.html#c:preload/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" to load the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \" association with our user.\"), mdx(\"p\", null, \"If you're not familiar with how relational databases handle associations, you can think of the association as a way of pointing to another struct (in our case, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" pointing to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \"), but without the need to copy the entire organization into the user. But, if you want to actually check to make sure that the organization is the one you're intending to reference (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user.owned_organization\"), \"), you need to load it into the user, otherwise the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owned_organization\"), \" of the user would not contain any data.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserTest do\\n  use PhoenixChat.ModelCase\\n\\n  alias PhoenixChat.{User, Organization, ConnCase}\\n\\n  @valid_attrs %{email: \\\"foo@bar.com\\\", encrypted_password: \\\"some content\\\", username: \\\"some content\\\"}\\n  @invalid_attrs %{}\\n\\n  test \\\"user can own an organization\\\" do\\n    user = ConnCase.create_user!\\n    org  = Repo.insert! %Organization{website: \\\"foo.com\\\", owner_id: user.id, public_key: \\\"test\\\"}\\n    user = Repo.preload(user, :owned_organization)\\n\\n    assert user.owned_organization == org\\n  end\\n\\n  test \\\"user belongs to organization\\\" do\\n    org  = Repo.insert! %Organization{website: \\\"foo.com\\\", public_key: \\\"test\\\"}\\n    user = ConnCase.create_user!(%{organization_id: org.id})\\n           |> Repo.preload(:organization)\\n\\n    assert user.organization == org\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Then we need to set up and alter a few of our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Organization\"), \" tests. The first change is to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"setup\"), \" block, in which we want to create a user for every test since every organization will need an owner. And since the database clears before every test, each new user will have an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"1\"), \". Because of that, we're adding \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"owner_id: 1\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@valid_attrs\"), \", which should reference the user created at the start of each test.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.OrganizationTest do\\n  use PhoenixChat.ModelCase\\n\\n  alias PhoenixChat.{Organization, ConnCase}\\n\\n  @valid_attrs %{website: \\\"foo.com\\\", owner_id: 1}\\n  @invalid_attrs %{}\\n\\n  setup do\\n    user = ConnCase.create_user!(%{id: 1})\\n    {:ok, %{user: user}}\\n  end\\n\\n  test \\\"organization belongs to owner\\\", %{user: user} do\\n    org = Repo.insert! %Organization{website: \\\"foo.com\\\", owner_id: user.id, public_key: \\\"test\\\"}\\n          |> Repo.preload(:owner)\\n\\n    assert org.owner == user\\n  end\\n\\n  test \\\"organization can have one admin\\\" do\\n    org  = Repo.insert! %Organization{website: \\\"foo.com\\\", public_key: \\\"test\\\"}\\n    user = ConnCase.create_user!(%{username: \\\"bar\\\", email: \\\"bar@foo.com\\\", organization_id: org.id})\\n\\n    org = Repo.preload(org, :admins)\\n\\n    assert org.admins == [user]\\n  end\\n\\n  test \\\"organization has many admins\\\" do\\n    org = Repo.insert! %Organization{website: \\\"foo.com\\\", public_key: \\\"test\\\"}\\n    user = ConnCase.create_user!(%{username: \\\"bar\\\", email: \\\"bar@foo.com\\\", organization_id: org.id})\\n    user2 = ConnCase.create_user!(%{username: \\\"baz\\\", email: \\\"baz@qux.com\\\", organization_id: org.id})\\n\\n    org = Repo.preload(org, :admins)\\n\\n    assert org.admins == [user, user2]\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Then we need to update a few of our other tests with the new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":owner_id\"), \" attribute so that their changeset becomes valid.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\ntest \\\"changeset must have a unique public key generated on create\\\" do\\n  changeset = Organization.changeset(%Organization{}, @valid_attrs)\\n  org1 = Repo.insert! changeset\\n\\n  changeset = Organization.changeset(%Organization{}, %{website: \\\"http://bar.com\\\", owner_id: 1})\\n  org2 = Repo.insert! changeset\\n\\n  assert org1.public_key != org2.public_key\\nend\\n\\ntest \\\"changeset's website must be a valid url\\\" do\\n  ...\\n\\n  for valid_url <- some_valid_urls do\\n    changeset = Organization.changeset(%Organization{}, %{website: valid_url, owner_id: 1})\\n\\n    assert changeset.valid?\\n  end\\nend\\n...\\n\")), mdx(\"p\", null, \"Now if you run your tests, all of your model tests will pass (though you should still have 5 errors since we haven't updated our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"OrganizationControllerTest\"), \").\"), mdx(\"p\", null, \"Also, make sure you run your migration!\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.migrate\\n\")), mdx(\"p\", null, \"The next step is to make our CRUD endpoints to allow our users to create a new organization. From there, our users will have access to their public key that they can use to populate their \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat\"), \" component and start sending and receiving messages routed to the proper organization.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Associate Organizations and Users Alter :users table Update models Update model tests Now that we have organizations set up, we need to…","frontmatter":{"title":"Associate Organizations and Users","order":41,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"associate-organizations-and-users","prevNode":{"frontmatter":{"title":"Testing with Elixir and Phoenix: Models","active":true,"free":false,"order":40,"tech":["phoenix","elixir"]},"fields":{"slug":"testing-with-elixir-and-phoenix-models"}},"nextNode":{"frontmatter":{"title":"Creating an Organization Model","active":true,"free":false,"order":41,"tech":["phoenix"]},"fields":{"slug":"creating-an-organization-model"}}}},"staticQueryHashes":["1723017916"]}