Create Anonymous User Model

  • Create anonymous users with fake data
  • Create and update models

At this point in our app, we have a functioning chat component and a backend that can handle messages. The next step is to add our anonymous users to a list and add them to our admin dashboard so our admin can start interacting with them.

But before we do that, we should give our anonymous users some fake information. Since it's hard to remember users based on uuids, we're going to give our users fake names and avatars for easier reference (if it's not clear to you why were are doing this, you'll see in a few lessons).

Add Faker

We're going to generate fake user data using the ubiquitous Faker package, which has an Elixir version. It's worth glancing over the docs to see how much fake data we have access to. Let's add that now.

...
def application do
[mod: {PhoenixChat, []},
applications: [
:comeonin,
:cowboy,
:faker,
:gettext,
...
]]
end
...
defp deps do
[
{:comeonin, "~> 2.3"},
{:corsica, "~> 0.4"},
{:cowboy, "~> 1.0"},
{:faker, "~> 0.7"},
{:gettext, "~> 0.11"},
...
]
end
...

Then be sure to run mix deps.get and restart your server.

$ mix deps.get

The next step is to generate two migrations: one to create an AnonymousUsers model and the other to associate that anonymous user with our existing Messages model.

$ mix ecto.gen.migration create_anonymous_user
$ mix ecto.gen.migration message_belongs_to_anonymous_user

We'll start with the anonymous user migration. We want to use the uuid as the primary key, which is a way of telling Ecto that the uuid is the unique identifier for each anonymous user. Ecto will, by default, use :id and a :integer as the primary key. Each user will also have a name and an avatar (both of which will be fake).

defmodule PhoenixChat.Repo.Migrations.CreateAnonymousUsers do
use Ecto.Migration
def change do
create table(:anonymous_users, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string
add :avatar, :string
timestamps
end
end
end

This should look familiar to you since it's basically the same as the other migrations we created. The next migration is a little bit more interesting and introduces a new concept that we haven't touched on before.

We need to alter the existing :messages table to add a reference to the new :anonymous_users we just created and remove the temporary :from field we added previously since we are now storing references from a separate table.

To do this, we need to create both up and down blocks. The code in the up block runs a migration as you would expect when you run mix ecto.migrate. The down block runs what is called a "down" migration, which you can think of as an "undo". In the event you screw up a migration, you can "rollback" your migrations and re-run them (hopefully) with the right data the next time.

In our up migration, we're adding the :anonymous_user_id to the :messages table and declaring that it references the :anonymous_user table we just created. We're also saying that when the referring anonymous user is deleted (on_delete), change all messages references to that user (which no longer exists) to nil.

In our down migration, we're saying, "if we have to undo this migration, remove the :anonymous_user_id from the messages table and add :from back to the table".

defmodule PhoenixChat.Repo.Migrations.MessageBelongsToAnonymousUser do
use Ecto.Migration
def up do
alter table(:messages) do
add :anonymous_user_id, references(:anonymous_users, on_delete: :nilify_all, type: :uuid)
remove :from
end
end
def down do
alter table(:messages) do
remove :anonymous_user_id
add :from, :string
end
end
end

Now that we have our migrations, we need to set up our AnonymousUser model and update our Message model to handle the new association.

Create and update models

Let's start by creating our AnonymousUser model.

$ touch web/models/anonymous_user.ex

Much of this should look familiar. We're creating has_many (docs) reference from our anonymous user to her messages, saying that each anonymous user can have many messages associated with her.

The only tricky part is that we're telling our model explicitly not to auto-generate a primary key since we're providing one with the uuid. The uuid is binary (a text string), so we need to specify @foreign_key_type to :binary_id because it defaults to :integer. In sum, we're telling @primary_key that the :id should not autogenerate and that it's a :binary_id.

In our changeset/2, we're referencing two functions that don't exist yet. We will create those below.

defmodule PhoenixChat.AnonymousUser do
use PhoenixChat.Web, :model
alias PhoenixChat.Message
@primary_key {:id, :binary_id, autogenerate: false}
@foreign_key_type :binary_id
schema "anonymous_users" do
field :name
field :avatar
has_many :messages, Message
timestamps
end
def changeset(model, params \\ :empty) do
model
|> cast(params, ~w(id), ~w())
|> put_avatar
|> put_name
end
end

Now we need to create two functions to add a name and an avatar to our new anonymous user: put_name/1 and put_avatar/1.

In put_name/1, we start by generating a fake name for our user. We do this by using Faker to generate a random color and a buzzword_suffix, which gives us fake names like:

  • Orange Alliance
  • Blue Framework
  • Purple Website

We don't care if they're unique since these are just for visual reference. From here, we use put_change/2 to add the :name to our changeset/2.

Then we use put_avatar/1 to do the same thing but for a 25 by 25 pixel image using Faker's image_url.

defmodule PhoenixChat.AnonymousUser do
...
defp put_name(changeset) do
adjective = Faker.Color.name |> String.capitalize
noun = Faker.Company.buzzword_suffix |> String.capitalize
name = adjective <> " " <> noun
changeset
|> put_change(:name, name)
end
defp put_avatar(changeset) do
changeset
|> put_change(:avatar, Faker.Avatar.image_url(25, 25))
end
end

We're also going to add an additional function that will come into play later. Rather than keep a separate table called something like :lobby, we can figure out who our recently active users are by finding the most recent messages and returning the users associated with those messages, with a default value of the 20 most recent users (detailed explanation below the code).

defmodule PhoenixChat.AnonymousUser do
...
@doc """
This query returns users with the most recent messages up to a given limit.
"""
def recently_active_users(limit \\ 20) do
from u in __MODULE__,
left_join: m in Message, on: m.anonymous_user_id == u.id,
distinct: u.id,
order_by: [desc: u.inserted_at, desc: m.inserted_at],
limit: ^limit
end
end

If you've worked a lot with SQL, this will look familiar to you. If this looks complicated, we'll go through it line-by-line.

In the first line, we start with from u in __MODULE__, which is our way of telling Ecto that we want to search through anything that matches our AnonymousUser struct. In other words, it will look through all of our anonymous users that we have stored in the database.

The next line uses a left_join, which is a SQL term that compares two tables and returns the first table along with anything that matches from the second table. For an excellent example of a left join, check out the docs from W3 Schools. In our case, we want to take our anonymous user's id and find all the messages associated with that user so we can determine which anonymous users have most recently sent a message.

Then we use distinct to make sure that all of the anonymous users are unique based on their ids. It's worth noting that that not all databases support distinct. We're using Postgres, which does support it.

Then we pass in order_by along with two elements in a list, which tell our anonymous users that we want to order them by most recent message, then by most recent addition to the database in descending order based on timestamp (inserted_at). This way, we prioritize users that have active conversations but still show users even if they haven't sent a message.

Finally, we limit the results to whatever was passed in, or default to 20 users. The caret (^) is required when passing a value into an Ecto query. Without the caret, Ecto will think the variable is part of the query syntax and not a value that you passed in.

Another thing to note is that Ecto does not care in which order you pass these arguments because it will prepare a SQL statement for you with the proper ordering. So, for example, you can have you limit statement before your order_by and it won't cause your results to be limited to 20 before they're ordered.

The last thing we need to do is update our Message model to handle the new association with anonymous users. The only difference here from previous associations is that we once again need to set the primary key using :type to a :binary_id since our uuid is a string.

defmodule PhoenixChat.Message do
use PhoenixChat.Web, :model
alias PhoenixChat.{DateTime, User, AnonymousUser}
schema "messages" do
field :body, :string
field :timestamp, DateTime
field :room, :string
belongs_to :user, User
belongs_to :anonymous_user, AnonymousUser, type: :binary_id
timestamps
end
@required_fields ~w(body timestamp room)
@optional_fields ~w(anonymous_user_id user_id)
...
end

Before you move on to the next lesson, be sure to run your migration.

$ mix ecto.migrate

Now we have a way to add anonymous users to our database, associate them with incoming messages, and return a list of our most recently active users. Keep in mind that the app is currently broken since we haven't updated our controllers.

Previous: Persist Messages to the DatabaseNext: Persist Anonymous Users