UUIDs as defaults for Ecto in Phoenix

Phoenix uses Postgres’ sequential auto-incrementing ids out of the box when creating database records. This is convenient, but auto-incrementing ids can be a dead giveaway to some business data you may not want to air so openly. Since by default the count is incremented by 1 for each new record in the database, it’s easy for users (or competition) to figure out how many Users, Posts, or Comments you have in your system when forming urls since they’ll end up like /user/37/comment (replace 37 with how many Users you have in your system, for example).

Fourk’s article on using UUIDs (universally unique identifier) is a good read - I won’t reiterate what they covered. You should read it. To make one thing clear is if you’ve already started your Phoenix app & want to make UUIDs the default for your models. To do so, navigate to <your_project>/web/web.ex and place the code below in the quote do block of the model function block.

@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id

Your model function block should look like below (including function definition):

def model do
  quote do
    use Ecto.Schema

    import Ecto
    import Ecto.Changeset
    import Ecto.Query

    @primary_key {:id, :binary_id, autogenerate: true}
    @foreign_key_type :binary_id
  end
end