Skip to content
BoogeyCodesPublic

About

A small polls API built with Ruby on Rails (API-only): create polls, vote once per voter, live results with percentages

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

QuickPoll

CI Ruby on Rails 7.1 Ruby 3.1+ License: MIT

Create a poll, share the link, and watch the votes land in real time. A full Ruby on Rails web app — with a clean JSON API underneath. No sign-up: one vote per person, kept honest by a signed cookie.

A QuickPoll results page

What it does

  • Create a poll with a question, two or more options, and an optional voting deadline.
  • Vote from any browser — one vote per visitor, enforced by a signed cookie (and by the API's voter_token), so nobody has to sign in and nobody can stuff the ballot.
  • Live results — the poll page refreshes counts, percentages and bars in place as votes arrive, and highlights the option in the lead.
  • Share a poll with a copy-paste link; close it by hand or let the deadline close it.

Voting on a poll The QuickPoll home page

Why

A polls app is a small domain with a surprisingly complete story, which makes it an honest demonstration of Rails end to end: associations between polls, options and votes; validations that enforce real rules ("one vote per voter", "an option must belong to its poll", "no voting once closed or expired"); a uniqueness constraint backed at both the model and database level; a server-rendered UI with a signed-cookie identity and CSRF protection; and the same domain exposed as a clean JSON API with a consistent error contract. The web UI and the API share one set of controllers and one results method — the formats diverge only at the edge.

Running locally

bundle install
bin/rails db:prepare
bin/rails server            # http://localhost:3000

Open the site, create a poll, and share the link. On Windows, the bundled tzinfo-data gem supplies the timezone database automatically.

The JSON API

Every page is also reachable as JSON (Accept: application/json or a .json suffix). The API is unchanged from 0.1 and needs no CSRF token.

GET    /polls              list polls, newest first
POST   /polls              create a poll { question, options: [..], expires_at? }  (>= 2 options)
GET    /polls/:id          a poll with results (counts and percentages)
POST   /polls/:id/close    close a poll to further voting
POST   /polls/:id/votes    cast a vote { option_id, voter_token }
GET    /up                 health check
# create a poll
curl -X POST localhost:3000/polls -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d '{"question":"Tabs or spaces?","options":["Tabs","Spaces"]}'

# vote (one vote per voter token per poll)
curl -X POST localhost:3000/polls/1/votes.json \
  -H 'Content-Type: application/json' \
  -d '{"option_id":1,"voter_token":"anon-abc"}'

# {"id":1,"question":"Tabs or spaces?","closed":false,"accepting_votes":true,
#  "expires_at":null,"total_votes":1,
#  "options":[{"id":1,"label":"Tabs","votes":1,"percentage":100.0},
#             {"id":2,"label":"Spaces","votes":0,"percentage":0.0}]}

Validation failures return 422 with an errors array; unknown records return 404. A second vote from the same voter_token returns { "errors": ["Voter token has already voted in this poll"] }.

Data model

Poll (question, closed, expires_at)
  has_many :options
  has_many :votes
  accepting_votes?  # not closed and not past its deadline

Option (poll_id, label)
  belongs_to :poll
  has_many :votes

Vote (poll_id, option_id, voter_token)
  belongs_to :poll, :option
  # unique on (poll_id, voter_token), in the model and as a DB index

Keeping poll_id on the vote (alongside option_id) is what lets "one vote per voter per poll" be a simple scoped uniqueness rule, enforced by both an ActiveRecord validation and a unique database index so a race cannot slip a duplicate through.

Rules enforced

  • A poll needs a question and at least two options.
  • A voter — identified by a signed cookie on the web, or an opaque voter_token on the API — may vote once per poll, but the same identity can vote in other polls.
  • A vote's option must belong to the poll it is cast in.
  • No votes once a poll is closed by hand or past its deadline.

Each rule is covered by a test.

How the web and API share controllers

The controllers derive the voter identity once — an explicit voter_token if given (the API), otherwise a stable per-browser id from a signed, long-lived cookie (the web) — then respond_to for the two formats:

poll.votes.create!(option: option, voter_token: resolve_voter_token)
respond_to do |format|
  format.html { redirect_to poll_path(poll), notice: "Thanks for voting!" }
  format.json { render json: poll.reload.results, status: :created }
end

CSRF protection is on for the browser (forms carry a token) and skipped for JSON clients. Live results are progressive enhancement: the page renders correct results server-side, and a small script polls the JSON view to keep them current — it works without JavaScript, just without the live update.

Testing

bin/rails db:prepare
bin/rails test

Forty-one tests with Rails' built-in Minitest: model tests for the vote rules, expiry and the results calculation; request tests that drive the JSON API end to end; and integration tests for the web flow — creating a poll from the form, cookie-keyed voting, the one-vote guarantee across a session, and the 404 page. CI runs the suite against a fresh SQLite database on every push.

Deployment

docker build -t quickpoll .
docker run -p 3000:3000 -e SECRET_KEY_BASE=$(openssl rand -hex 64) quickpoll

The image migrates the database on boot and serves with Puma. Provide SECRET_KEY_BASE in production (it signs the voter cookie and session).

Project layout

app/models        Poll, Option, Vote (associations, validations, expiry)
app/controllers   Polls/Votes/Application — one set of controllers, HTML + JSON
app/views         layout, home, new, show, results partial (inline-styled, no asset pipeline)
config/routes.rb  root + nested RESTful routes
db/migrate        polls/options/votes, the unique vote index, and the expiry column
test/             model, request (API) and integration (web) tests

License

MIT

About

A small polls API built with Ruby on Rails (API-only): create polls, vote once per voter, live results with percentages

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages