-
-
Notifications
You must be signed in to change notification settings - Fork 80
Description
Linter Rule: Prefer explicit route helpers over implicit polymorphic URLs
Rule: erb-no-implicit-polymorphic-url
Description
Prefer using explicit Rails route helpers (e.g., profile_path(@profile)) over passing model objects directly to link_to, which relies on implicit polymorphic routing to generate the URL.
Rationale
When you pass a model object directly to link_to (e.g., <%= link_to "Profile", @profile %>), Rails uses polymorphic_path behind the scenes to infer the URL. While convenient, this implicit behavior makes it unclear what URL will be generated, a reader must know the model's class and routing conventions to determine the target path.
Implicit routing also depends on the model's class name matching a route, so renaming a model, using STI, or introducing namespaced routes can silently break the generated URL. Explicit route helpers like profile_path are easy to grep for across the codebase, making it straightforward to find all links to a given resource. They make the developer's intent unambiguous, reducing the chance of subtle routing bugs.
Using explicit route helpers also enables better static analysis. Tools like Herb can determine the target path from the helper name alone without needing to resolve the model's class at runtime, making it possible to detect broken links, analyze navigation structure, and provide more accurate diagnostics.
Notes
This rule only applies when a model object (e.g., @profile, @user) is passed as the URL argument to link_to. Using link_to with an explicit named route helper like articles_path or a hardcoded string path like "/articles" is perfectly fine and will not trigger this rule.
Examples
✅ Good
<%= link_to "Profile", profile_path(@profile) %><%= link_to "Edit Profile", edit_profile_path(@profile) %><%= link_to @user.name, user_path(@user) %><%= link_to "View Post", post_path(@post), class: "btn" %><%= link_to "Articles", articles_path %><%= link_to "Articles", "/articles" %>🚫 Bad
<%= link_to @profile %><%= link_to "Profile", @profile %><%= link_to @user.name, @user %><%= link_to "View Post", @post, class: "btn" %>