iTranslated by AI
Simplifying complex path helpers with polymorphic_path
What's the Benefit?
When multiple models (e.g., "general users" and "admin users") can operate on data like "articles" or "comments", you can create URLs without needing to be aware of which model is being used.
As a result, you can avoid using long and complex helpers like xxx_xxx_xxx_path.
Example
For instance, consider a case where both "general users" and "admin users" can add "comments" to "articles".
resources :articles do
resources :comments
end
namespace :admin do
resources :articles do
resources :comments
end
end
The following _path helpers become available:
When Admin Users operate on comments for articles
# List display
admin_article_comments_path(@article)
# When creating
new_admin_article_comment_path(@article)
# When editing
edit_admin_article_comment_path(@article, @comment)
When General Users operate on comments for articles
# List display
article_comments_path(@article)
# When creating
new_article_comment_path(@article)
# When editing
edit_article_comment_path(@article, @comment)
However, as nesting gets deeper, helper names become longer and more complex. I was wondering if there was a better way, and then I learned about a method that allows you to write them without worrying about the helper names: using polymorphic_path.
When using polymorphic_path
When using polymorphic_path, helper names become simpler as shown below.
Path generation when admin users operate on comments for articles
# List display
polymorphic_path([:admin, @article, :comments])
# When creating
new_polymorphic_path([:admin, @article, :comment])
# When editing
edit_polymorphic_path([:admin, @article, @comment])
Path generation when general users operate on comments for articles
# List display
polymorphic_path([@article, :comments])
# When creating
new_polymorphic_path([@article, :comment])
# When editing
edit_polymorphic_path([@article, @comment])
This is convenient, isn't it?
By the way, if you want to use the _url helper, you can use polymorphic_url.
Official documentation
Discussion