{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/create-anonymous-user-model","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\": \"Create Anonymous User Model\",\n  \"order\": 29,\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, \"Create Anonymous User Model\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Create anonymous users with fake data\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Create and update models\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"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).\"), mdx(\"h2\", null, \"Add Faker\"), mdx(\"p\", null, \"We're going to generate fake user data using the ubiquitous \", mdx(\"a\", {\n    \"href\": \"https://github.com/igas/faker\",\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  def application do\\n    [mod: {PhoenixChat, []},\\n      applications: [\\n        :comeonin,\\n        :cowboy,\\n        :faker,\\n        :gettext,\\n        ...\\n      ]]\\n  end\\n...\\n  defp deps do\\n    [\\n      {:comeonin, \\\"~> 2.3\\\"},\\n      {:corsica, \\\"~> 0.4\\\"},\\n      {:cowboy, \\\"~> 1.0\\\"},\\n      {:faker, \\\"~> 0.7\\\"},\\n      {:gettext, \\\"~> 0.11\\\"},\\n      ...\\n    ]\\n  end\\n...\\n\")), mdx(\"p\", null, \"Then be sure to run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix deps.get\"), \" and restart your server.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix deps.get\\n\")), mdx(\"p\", null, \"The next step is to generate two migrations: one to create an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AnonymousUsers\"), \" model and the other to associate that anonymous user with our existing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Messages\"), \" model.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.gen.migration create_anonymous_user\\n$ mix ecto.gen.migration message_belongs_to_anonymous_user\\n\")), mdx(\"p\", null, \"We'll start with the anonymous user migration. We want to use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" as the \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Schema.html\",\n    \"parentName\": \"p\"\n  }, \"primary key\"), \", which is a way of telling Ecto that the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" is the unique identifier for each anonymous user. Ecto will, by default, use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":id\"), \" and a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":integer\"), \" as the primary key. Each user will also have a name and an avatar (both of which will be fake).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Repo.Migrations.CreateAnonymousUsers do\\n  use Ecto.Migration\\n\\n  def change do\\n    create table(:anonymous_users, primary_key: false) do\\n      add :id, :uuid, primary_key: true\\n      add :name, :string\\n      add :avatar, :string\\n\\n      timestamps\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"We need to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"alter\"), \" the existing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":messages\"), \" table to add a reference to the new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":anonymous_users\"), \" we just created and remove the temporary \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":from\"), \" field we added previously since we are now storing references from a separate table.\"), mdx(\"p\", null, \"To do this, we need to create both \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"up\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"down\"), \" blocks. The code in the \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Migrator.html#up/4\",\n    \"parentName\": \"p\"\n  }, \"up\"), \" block runs a migration as you would expect when you run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix ecto.migrate\"), \". The \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Migrator.html#down/4\",\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"In our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"up\"), \" migration, we're adding the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":anonymous_user_id\"), \" to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":messages\"), \" table and declaring that it references the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":anonymous_user\"), \" table we just created. We're also saying that when the referring anonymous user is deleted (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"on_delete\"), \"), change all messages references to that user (which no longer exists) to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \".\"), mdx(\"p\", null, \"In our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"down\"), \" migration, we're saying, \\\"if we have to undo this migration, remove the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":anonymous_user_id\"), \" from the messages table and add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":from\"), \" back to the table\\\".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Repo.Migrations.MessageBelongsToAnonymousUser do\\n  use Ecto.Migration\\n\\n  def up do\\n    alter table(:messages) do\\n      add :anonymous_user_id, references(:anonymous_users, on_delete: :nilify_all, type: :uuid)\\n      remove :from\\n    end\\n  end\\n\\n  def down do\\n    alter table(:messages) do\\n      remove :anonymous_user_id\\n      add :from, :string\\n    end\\n  end\\nend\\n\")), mdx(\"p\", null, \"Now that we have our migrations, we need to set up our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AnonymousUser\"), \" model and update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Message\"), \" model to handle the new association.\"), mdx(\"h2\", null, \"Create and update models\"), mdx(\"p\", null, \"Let's start by creating our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AnonymousUser\"), \" model.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch web/models/anonymous_user.ex\\n\")), mdx(\"p\", null, \"Much of this should look familiar. We're creating \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"has_many\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" reference from our anonymous user to her messages, saying that each anonymous user can have many messages associated with her.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@foreign_key_type\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":binary_id\"), \" because it defaults to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":integer\"), \". In sum, we're telling \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@primary_key\"), \" that the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":id\"), \" should not \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"autogenerate\"), \" and that it's a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":binary_id\"), \".\"), mdx(\"p\", null, \"In our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \", we're referencing two functions that don't exist yet. We will create those below.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AnonymousUser do\\n  use PhoenixChat.Web, :model\\n\\n  alias PhoenixChat.Message\\n\\n  @primary_key {:id, :binary_id, autogenerate: false}\\n  @foreign_key_type :binary_id\\n\\n  schema \\\"anonymous_users\\\" do\\n    field :name\\n    field :avatar\\n    has_many :messages, Message\\n\\n    timestamps\\n  end\\n\\n  def changeset(model, params \\\\\\\\ :empty) do\\n    model\\n    |> cast(params, ~w(id), ~w())\\n    |> put_avatar\\n    |> put_name\\n  end\\nend\\n\")), mdx(\"p\", null, \"Now we need to create two functions to add a name and an avatar to our new anonymous user: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_name/1\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_avatar/1\"), \".\"), mdx(\"p\", null, \"In \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_name/1\"), \", we start by generating a fake name for our user. We do this by using Faker to generate a random \", mdx(\"a\", {\n    \"href\": \"https://github.com/igas/faker/blob/master/lib/faker/color/en.ex\",\n    \"parentName\": \"p\"\n  }, \"color\"), \" and a \", mdx(\"a\", {\n    \"href\": \"https://github.com/igas/faker/blob/master/lib/faker/company/en.ex\",\n    \"parentName\": \"p\"\n  }, \"buzzword_suffix\"), \", which gives us fake names like:\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Orange Alliance\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Blue Framework\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Purple Website\")), mdx(\"p\", null, \"We don't care if they're unique since these are just for visual reference. From here, we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_change/2\"), \" to add the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":name\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset/2\"), \".\"), mdx(\"p\", null, \"Then we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_avatar/1\"), \" to do the same thing but for a 25 by 25 pixel image using Faker's \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/faker/Faker.Avatar.html#image_url/2\",\n    \"parentName\": \"p\"\n  }, \"image_url\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AnonymousUser do\\n\\n  ...\\n\\n  defp put_name(changeset) do\\n    adjective = Faker.Color.name |> String.capitalize\\n    noun = Faker.Company.buzzword_suffix |> String.capitalize\\n    name = adjective <> \\\" \\\" <> noun\\n    changeset\\n    |> put_change(:name, name)\\n  end\\n\\n  defp put_avatar(changeset) do\\n    changeset\\n    |> put_change(:avatar, Faker.Avatar.image_url(25, 25))\\n  end\\nend\\n\")), mdx(\"p\", null, \"We're also going to add an additional function that will come into play later. Rather than keep a separate table called something like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":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).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AnonymousUser do\\n\\n  ...\\n\\n  @doc \\\"\\\"\\\"\\n  This query returns users with the most recent messages up to a given limit.\\n  \\\"\\\"\\\"\\n  def recently_active_users(limit \\\\\\\\ 20) do\\n    from u in __MODULE__,\\n      left_join: m in Message, on: m.anonymous_user_id == u.id,\\n      distinct: u.id,\\n      order_by: [desc: u.inserted_at, desc: m.inserted_at],\\n      limit: ^limit\\n  end\\nend\\n\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"In the first line, we start with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from u in __MODULE__\"), \", which is our way of telling Ecto that we want to search through anything that matches our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AnonymousUser\"), \" struct. In other words, it will look through all of our anonymous users that we have stored in the database.\"), mdx(\"p\", null, \"The next line uses a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"a\", {\n    \"href\": \"http://www.w3schools.com/sql/sql_join_left.asp\",\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"Then we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"distinct\"), \". We're using Postgres, which does support it.\"), mdx(\"p\", null, \"Then we pass in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"inserted_at\"), \"). This way, we prioritize users that have active conversations but still show users even if they haven't sent a message.\"), mdx(\"p\", null, \"Finally, we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"limit\"), \" the results to whatever was passed in, or default to 20 users. The caret (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"^\"), \") 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.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"limit\"), \" statement before your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"order_by\"), \" and it won't cause your results to be limited to 20 before they're ordered.\"), mdx(\"p\", null, \"The last thing we need to do is update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":type\"), \" to a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":binary_id\"), \" since our uuid is a string.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Message do\\n  use PhoenixChat.Web, :model\\n\\n  alias PhoenixChat.{DateTime, User, AnonymousUser}\\n\\n  schema \\\"messages\\\" do\\n    field :body, :string\\n    field :timestamp, DateTime\\n    field :room, :string\\n\\n    belongs_to :user, User\\n    belongs_to :anonymous_user, AnonymousUser, type: :binary_id\\n\\n    timestamps\\n  end\\n\\n  @required_fields ~w(body timestamp room)\\n  @optional_fields ~w(anonymous_user_id user_id)\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Before you move on to the next lesson, be sure to run your migration.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.migrate\\n\")), mdx(\"p\", null, \"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.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Create Anonymous User Model Create anonymous users with fake data Create and update models At this point in our app, we have a functioning…","frontmatter":{"title":"Create Anonymous User Model","order":29,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"create-anonymous-user-model","prevNode":{"frontmatter":{"title":"Persist Messages to the Database","active":true,"free":false,"order":28,"tech":["phoenix","postgres"]},"fields":{"slug":"persist-messages-to-the-database"}},"nextNode":{"frontmatter":{"title":"Persist Anonymous Users","active":true,"free":false,"order":30,"tech":["phoenix"]},"fields":{"slug":"persist-anonymous-users"}}}},"staticQueryHashes":["1723017916"]}