In an Active Record model, how does to_param decide the :id that Rails URL helpers generate, and how do you produce /class_sessions/42-sunrise-flow?
answer
- helpers call to_param on records
- default is the id as a string
- nil for an unsaved record
- to_param :title class macro
- find still casts the leading digits
basics
~20 sURL helpers call to_param on a record, which returns its id as a string. Declaring to_param :title in the model (or overriding the method) yields "42-sunrise-flow", and ClassSession.find still works because the leading digits cast to 42.
solid answer
~40 sWhen you pass a record to `class_session_path`, Rails fills `:id` with `record.to_param`. Active Record's default returns the primary key as a string, or nil when there is no id yet, which is why linking to an unsaved record fails. For readable URLs, the class macro `to_param :title` makes `to_param` return `"42-sunrise-flow"`: the id, a dash and the parameterized title, truncated by word to 20 characters. Because the value starts with the id, `ClassSession.find(params[:id])` keeps working: the string casts to the integer 42. If you override `to_param` to return only a slug, `find` no longer works; look the record up with `find_by!(slug: params[:id])`, keep the slug unique and stable, and accept that changing it breaks old links.
code
ruby · 10 linesclass ClassSession < ApplicationRecord
to_param :title
end
session = ClassSession.create!(title: "Sunrise Flow")
session.to_param # => "42-sunrise-flow"
Rails.application.routes.url_helpers.class_session_path(session)
# => "/class_sessions/42-sunrise-flow"
ClassSession.find("42-sunrise-flow") == session # => true
ClassSession.new.to_param # => nilgo deeper
Recall that helpers call to_param on records and that it returns the id as a string by default.
Explain the to_param :title macro, why find still works with the id prefix, and why an unsaved record cannot fill :id.
Weigh id-prefixed slugs against slug-only URLs: unique stable slugs, changed lookups, canonical redirects and broken links after renames.
Set the app's URL identity policy, balancing shareable readable links against stability, enumeration risk and migration cost.
## Where the :id in a URL comes from A resource route has a dynamic `:id` segment, as in `/class_sessions/:id`. When you pass a **record** to a helper, Rails does not read `record.id` directly; it calls **`to_param`** and puts the result into the segment (escaping it for the URL). - Active Record's default `to_param` returns the primary key as a **string**: `"42"`. - A record with **no id** (unsaved) returns `nil`, so a helper that needs `:id` cannot build the URL and raises `ActionController::UrlGenerationError` about the missing required key. - For a **composite primary key**, the parts are joined with a dash by default. - Plain objects work too: any value that responds to `to_param` can be passed, and Active Support defines it on everyday objects (an Integer gives its string form). ## Readable URLs with the class macro The yoga-studio app wants share-friendly links such as `/class_sessions/42-sunrise-flow`. Active Record has a class-level macro for exactly this: ```ruby class ClassSession < ApplicationRecord to_param :title end session = ClassSession.find(42) # title: "Sunrise Flow" session.to_param # => "42-sunrise-flow" ``` What the macro does: 1. Calls the default `to_param` to get the id. 2. Reads the named attribute, squishes it and runs `parameterize` (lower case, dashes for spaces, unsafe characters removed). 3. **Truncates** the slug to 20 characters, cutting at a dash so words stay whole. 4. Returns `"#{id}-#{slug}"`, or just the id when the attribute is blank. The id stays in front, so lookups keep working unchanged: ```ruby ClassSession.find("42-sunrise-flow") # casts to 42 and finds the record ``` The integer cast reads the leading digits and ignores the rest, which also means `/class_sessions/42-anything` finds the same record. Most apps accept that; if the canonical form matters, the controller can redirect when `params[:id]` differs from `@session.to_param`. ## Slug-only URLs Some apps want `/class_sessions/sunrise-flow` with no id. Override the method and change the lookup: ```ruby class ClassSession < ApplicationRecord def to_param = slug end # controller @session = ClassSession.find_by!(slug: params[:id]) ``` That choice brings obligations: - the slug column needs a **unique index** and a value for every row; - it must be **URL-safe**, so generate it with `parameterize`; - it should be **stable**: changing a title must not silently change the slug, or every shared link breaks; - `find(params[:id])` no longer works, so every controller that loads the record must change. Renaming the segment itself from `:id` to `:slug` is done with the `param:` option on `resources`, which is a route-definition matter; `to_param` only decides the value. ## Comparing the options | Approach | URL | Lookup | Survives a title change? | |---|---|---|---| | Default | `/class_sessions/42` | `find` | yes | | `to_param :title` | `/class_sessions/42-sunrise-flow` | `find` | yes, old links still resolve by id | | Slug-only override | `/class_sessions/sunrise-flow` | `find_by!(slug:)` | only if the slug is kept stable | ## Keeping one canonical URL Because `find` ignores everything after the id, `/class_sessions/42-old-title` and `/class_sessions/42-sunrise-flow` both load the same record. To keep search engines and shared links on one form, compare the incoming value with the current `to_param` and redirect when they differ: ```ruby def show @session = ClassSession.find(params[:id]) if params[:id] != @session.to_param redirect_to @session, status: :moved_permanently end end ``` This also handles renamed titles gracefully: old links keep working because the id still resolves, and visitors land on the current slug. ## Things to check - **Every link changes at once.** `to_param` is used by every helper, `redirect_to`, `link_to` and `form_with` for that model, which is the point, but also means tests that assert literal URLs need updating. - **Do not put secrets or private data in a slug**; URLs end up in logs, referrers and calendar invites. - **Do not rely on `to_param` for authorization.** A guessable id is no worse than a slug; access control still belongs in the controller. `to_param` is a small hook with a large reach: one method decides how every URL for a model looks.
- Why does class_session_path(ClassSession.new) raise an error in Rails?An unsaved record has no id, so `to_param` returns nil and the show route's required `:id` segment has no value. Generation raises `ActionController::UrlGenerationError` about missing required keys. Link to the collection or the `new` route instead, which is what polymorphic routing does automatically for a new record.
- In Active Record, what does to_param :title return when the title is "Restorative Yin and Yoga Nidra"?The slug is parameterized to `restorative-yin-and-yoga-nidra` and then truncated to at most 20 characters at a dash, giving `restorative-yin-and`, so `to_param` returns something like `"42-restorative-yin-and"`. The id comes first, so lookups by `find` still work however the slug is cut.
to_param is the label printed on a locker door: staff still find the locker by its number, and adding a name after the number makes it friendlier without changing how it is found.
- URL helpers read record.id directly and ignore to_param
- After to_param :title, ClassSession.find needs the exact full slug
- Overriding to_param also renames the :id segment in the route
- An unsaved record's to_param is "new"
- A slug in to_param makes the record private to people without the link