Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: A Live Poll with LiveView and PubSub

Build a real-time poll in Phoenix: Ecto schemas, a context with validation, a LiveView page, PubSub broadcasts so every viewer sees votes appear instantly.

In this project you will build a poll page where visitors pick an option and everyone watching sees the bars move immediately. It uses what the earlier chapters taught: an Ecto schema and changeset, a context, a LiveView and PubSub.

Phoenix, Ecto and a database cannot run on this site, so the Elixir code is read-only and complete enough to type into a real project. The runnable editors implement the same design (context, validation, broadcast, two "browser tabs") in JavaScript so you can test the logic here.

The plan

flowchart LR
  A["Visitor clicks an option"] --> B["LiveView handle_event vote"]
  B --> C["Polls.vote/2 in the context"]
  C --> D["Repo insert and update"]
  C --> E["PubSub broadcast poll:ID"]
  E --> F["Every LiveView handle_info"]
  F --> G["Bars re-render"]

The context does the work and the broadcast; LiveViews only react.

1. Generate the data layer

A poll has many options, and each option counts votes. Using a counter column is simple and fast; a unique-votes rule would need a votes table (an exercise at the end).

Terminal
mix phx.gen.context Polls Poll polls question:string
mix phx.gen.context Polls Option options poll_id:references:polls label:string votes:integer
mix ecto.migrate

Edit the option migration so the counter has a default, and add an index:

ELIXIR
add :votes, :integer, null: false, default: 0
create index(:options, [:poll_id])

The schemas:

ELIXIR
defmodule MyApp.Polls.Poll do
  use Ecto.Schema
  import Ecto.Changeset

  schema "polls" do
    field :question, :string
    has_many :options, MyApp.Polls.Option
    timestamps()
  end

  def changeset(poll, attrs) do
    poll
    |> cast(attrs, [:question])
    |> validate_required([:question])
    |> validate_length(:question, min: 5, max: 140)
  end
end

defmodule MyApp.Polls.Option do
  use Ecto.Schema

  schema "options" do
    field :label, :string
    field :votes, :integer, default: 0
    belongs_to :poll, MyApp.Polls.Poll
    timestamps()
  end
end

2. The context: vote and broadcast

The important function is vote/1. It increments atomically in the database, so two simultaneous votes never overwrite each other, then broadcasts the fresh poll.

ELIXIR
defmodule MyApp.Polls do
  import Ecto.Query
  alias MyApp.Repo
  alias MyApp.Polls.{Poll, Option}

  def get_poll!(id), do: Poll |> Repo.get!(id) |> Repo.preload(options: from(o in Option, order_by: o.id))

  def subscribe(poll_id), do: Phoenix.PubSub.subscribe(MyApp.PubSub, "poll:#{poll_id}")

  def vote(option_id) do
    {count, _} =
      from(o in Option, where: o.id == ^option_id)
      |> Repo.update_all(inc: [votes: 1])

    case count do
      1 ->
        option = Repo.get!(Option, option_id)
        poll = get_poll!(option.poll_id)
        Phoenix.PubSub.broadcast(MyApp.PubSub, "poll:#{poll.id}", {:poll_updated, poll})
        {:ok, poll}

      0 ->
        {:error, :not_found}
    end
  end
end

update_all with inc: becomes UPDATE options SET votes = votes + 1, which is atomic. Reading, adding one in Elixir and saving would lose votes under load.

3. The LiveView

ELIXIR
defmodule MyAppWeb.PollLive do
  use MyAppWeb, :live_view
  alias MyApp.Polls

  def mount(%{"id" => id}, _session, socket) do
    poll = Polls.get_poll!(id)
    if connected?(socket), do: Polls.subscribe(poll.id)
    {:ok, assign(socket, poll: poll, voted: false)}
  end

  def handle_event("vote", %{"id" => option_id}, socket) do
    case Polls.vote(String.to_integer(option_id)) do
      {:ok, poll} -> {:noreply, assign(socket, poll: poll, voted: true)}
      {:error, :not_found} -> {:noreply, put_flash(socket, :error, "That option is gone.")}
    end
  end

  def handle_info({:poll_updated, poll}, socket), do: {:noreply, assign(socket, :poll, poll)}

  defp total(poll), do: Enum.sum(Enum.map(poll.options, & &1.votes))
  defp percent(_votes, 0), do: 0
  defp percent(votes, total), do: round(votes * 100 / total)

  def render(assigns) do
    ~H"""
    <h1><%= @poll.question %></h1>
    <ul>
      <li :for={o <- @poll.options}>
        <button phx-click="vote" phx-value-id={o.id} disabled={@voted}><%= o.label %></button>
        <div class="bar" style={"width: #{percent(o.votes, total(@poll))}%"}></div>
        <span><%= o.votes %> (<%= percent(o.votes, total(@poll)) %>%)</span>
      </li>
    </ul>
    """
  end
end

Add live "/polls/:id", PollLive to the router. The same handle_info that updates other viewers also covers the voter's own tab, because the broadcast reaches every subscriber, including the one that voted. In handle_event we assign the result too, so the click feels instant even before the broadcast arrives.

Setting voted: true only disables the button for this page. A visitor can reload and vote again. Real one-vote-per-person needs a votes table with a unique index on (poll_id, user_id) or on a signed cookie token; see the exercises.

4. A runnable model of the whole flow

This version has a database (an object), the vote context function with the same success and failure shapes, a PubSub, and two simulated LiveViews rendering text bars.

Node.js Poll context, PubSub and two viewers (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

5. Testing the context

The behavior that matters is the counter and the not-found case. Context tests are fast and need no browser (see testing contexts):

ELIXIR
test "vote/1 increments and broadcasts" do
  poll = poll_fixture(options: ["A", "B"])
  Polls.subscribe(poll.id)
  [a, _b] = poll.options

  assert {:ok, updated} = Polls.vote(a.id)
  assert Enum.find(updated.options, &(&1.id == a.id)).votes == 1
  assert_receive {:poll_updated, %{id: id}} when id == poll.id
end

This second model proves the atomic-increment point: with read-modify-write, concurrent votes get lost; with an in-database increment, they all count.

Node.js Lost updates vs atomic increment (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercises

  1. Add a votes table (poll_id, voter_token) with a unique index and reject a second vote from the same cookie token.
  2. Replace the percent bars with a LiveView stream of recent votes.
  3. Add a form with to_form/2 that creates polls with 2 to 6 options (see forms).
  4. Close a poll after a deadline and show the final result only.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does vote/1 use update_all with inc: instead of reading the option and saving votes + 1?

    Read-modify-write can overwrite another request's vote. UPDATE ... SET votes = votes + 1 cannot.
  2. 2. Where does the broadcast happen, and why?

    Keeping it next to the database change means any caller of vote/1 triggers the update.
  3. 3. When should the LiveView subscribe to the topic?

    The first static render has no process that stays alive, so only the connected mount subscribes.
  4. 4. What does voted: true in this project prevent?

    Real one-vote-per-person rules need server-side storage and a unique constraint.

Summary

  • Model the poll with two schemas and keep all writes in a Polls context.
  • Increment counters atomically in the database.
  • Broadcast from the context; LiveViews subscribe in the connected mount and update in handle_info/2.
  • Test the context directly; UI details can be tested with LiveViewTest.

Next: Project: A Chat Room with Channels and Presence