Associate Organizations and Users

  • Alter :users table
  • Update models
  • Update model tests

Now that we have organizations set up, we need to associate our 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).

Alter :users table

The first and most straightforward thing to do is to generate a new migration and alter the existing :users table to include a new field for :organization_id so we know to which organization this user belongs.

$ mix ecto.gen.migration add_organization_reference_in_user

Then we alter the :users table and add an :organization_id which references our :organizations table. We're also setting an option to nilify_all so when a user is deleted, all of the user's owned organizations will have their owner_id set to nil. We do this since we want users whose organizations have been deleted to have a nil value rather than continue to reference a non-existent user.

defmodule PhoenixChat.Repo.Migrations.AddOrganizationReferenceInUser do
use Ecto.Migration
def change do
alter table(:users) do
add :organization_id, references(:organizations, on_delete: :nilify_all)
end
end
end

Now we need to update our models to reflect this change.

Update User and Organization models

The first change we'll make is to the User model, in which we will add an association between our User model and our Organization model. In this case, we're adding a has_one association between the Organization and the User, signifying that each user may only own one organization. Then we're adding a belongs_to association to link our users to a particular organization.

For a more detailed explanation of the belongs_to/3 function, here's one from the Ecto docs.

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.

We're also going to associate our organizations with our users.

defmodule PhoenixChat.User do
use PhoenixChat.Web, :model
alias PhoenixChat.Organization
schema "users" do
field :email, :string
field :encrypted_password, :string
field :username, :string
field :password, :string, virtual: true
has_one :owned_organization, Organization, foreign_key: :owner_id
belongs_to :organization, Organization
timestamps
end
...
end

Then within our Organization model, we add a has_many association with :admins with the :organization_id as the foreign key, telling our Organization schema that it should expect to have (potentially) many admins. We also say that an organization belongs_to whichever User is the :owner_id foreign key that we set above in our User model.

We're also going to adjust our changeset to require an :owner_id when an organization is created because we don't want organizations without an owner.

defmodule PhoenixChat.Organization do
use PhoenixChat.Web, :model
alias PhoenixChat.{User, Repo}
schema "organizations" do
field :public_key, :string
field :website, :string
has_many :admins, User, foreign_key: :organization_id
belongs_to :owner, User, foreign_key: :owner_id
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:website, :owner_id])
|> validate_required([:website, :owner_id])
|> update_change(:website, &set_uri_scheme/1)
|> validate_change(:website, &validate_website/2)
|> unique_constraint(:website)
|> put_public_key()
|> unique_constraint(:public_key)
end
...
end

The last thing we should do before proceeding is update our model tests with these new associations.

Update model tests

We'll start with the User tests because they're simpler.

Our first test checks to make sure that we can create an organization with an :owner_id that references a user. In order to do this, we need to use Repo.preload/3 (docs) to load the :owned_organization association with our user.

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, User pointing to 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 (user.owned_organization), you need to load it into the user, otherwise the :owned_organization of the user would not contain any data.

defmodule PhoenixChat.UserTest do
use PhoenixChat.ModelCase
alias PhoenixChat.{User, Organization, ConnCase}
@valid_attrs %{email: "foo@bar.com", encrypted_password: "some content", username: "some content"}
@invalid_attrs %{}
test "user can own an organization" do
user = ConnCase.create_user!
org = Repo.insert! %Organization{website: "foo.com", owner_id: user.id, public_key: "test"}
user = Repo.preload(user, :owned_organization)
assert user.owned_organization == org
end
test "user belongs to organization" do
org = Repo.insert! %Organization{website: "foo.com", public_key: "test"}
user = ConnCase.create_user!(%{organization_id: org.id})
|> Repo.preload(:organization)
assert user.organization == org
end
...
end

Then we need to set up and alter a few of our Organization tests. The first change is to our 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 id of 1. Because of that, we're adding owner_id: 1 to our @valid_attrs, which should reference the user created at the start of each test.

defmodule PhoenixChat.OrganizationTest do
use PhoenixChat.ModelCase
alias PhoenixChat.{Organization, ConnCase}
@valid_attrs %{website: "foo.com", owner_id: 1}
@invalid_attrs %{}
setup do
user = ConnCase.create_user!(%{id: 1})
{:ok, %{user: user}}
end
test "organization belongs to owner", %{user: user} do
org = Repo.insert! %Organization{website: "foo.com", owner_id: user.id, public_key: "test"}
|> Repo.preload(:owner)
assert org.owner == user
end
test "organization can have one admin" do
org = Repo.insert! %Organization{website: "foo.com", public_key: "test"}
user = ConnCase.create_user!(%{username: "bar", email: "bar@foo.com", organization_id: org.id})
org = Repo.preload(org, :admins)
assert org.admins == [user]
end
test "organization has many admins" do
org = Repo.insert! %Organization{website: "foo.com", public_key: "test"}
user = ConnCase.create_user!(%{username: "bar", email: "bar@foo.com", organization_id: org.id})
user2 = ConnCase.create_user!(%{username: "baz", email: "baz@qux.com", organization_id: org.id})
org = Repo.preload(org, :admins)
assert org.admins == [user, user2]
end
...
end

Then we need to update a few of our other tests with the new :owner_id attribute so that their changeset becomes valid.

...
test "changeset must have a unique public key generated on create" do
changeset = Organization.changeset(%Organization{}, @valid_attrs)
org1 = Repo.insert! changeset
changeset = Organization.changeset(%Organization{}, %{website: "http://bar.com", owner_id: 1})
org2 = Repo.insert! changeset
assert org1.public_key != org2.public_key
end
test "changeset's website must be a valid url" do
...
for valid_url <- some_valid_urls do
changeset = Organization.changeset(%Organization{}, %{website: valid_url, owner_id: 1})
assert changeset.valid?
end
end
...

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 OrganizationControllerTest).

Also, make sure you run your migration!

$ mix ecto.migrate

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 phoenix-chat component and start sending and receiving messages routed to the proper organization.

Previous: Testing with Elixir and Phoenix: ModelsNext: Creating an Organization Model