29 February 2016 · About 1 minute read

Rails: Generating Polymorphic URLs when Model name does not match Route

Given a slugged generic model for which you want to generate a URL at runtime, you can usually just call:

@b = BlogPost.find(params[:id])
# ==> BlogPost[id: 100, slug: "hello-world"]

polymorphic_url(b)
# ==> blog_post_url(b.id)
# ==> "/blog_posts/hello-world"

However, I recently came across a case where the named route did not match the model name. Using the above as an example:

# config/routes.rb
resources :blog_posts, as: 'posts'

Unfortunately, calling polymorphic_path now throws an error complaining that the generated path method (blog_post_url) does not exist. The path name, which is inferred through the model class BlogPost no longer matches any routes.

Instead, we needed the method to be post_url.

Thankfully, polymorphic_url lets you supply the path as a symbol, rather than inferring it from the model. We can then pass the additional information (in this case, the slug parameter) to the helper as an argument:

polymorphic_url([b.model_name.human.underscore.to_sym], id: b.slug)

==> post_url(b.id)
==> "/posts/hello-world"

Learn how to keep your Rails apps fast, secure and running in top condition.

The Ruby and Rails worlds move fast, so it can feel like no time at all before your app starts to feel left behind.

Slow pages, memory, new gems, a constant stream of security patches, changing third-party APIs, and growing demands on your server's resources all work tirelessly against your app.

While your app launched with a strong foundation— the latest gems, employing best practices, and developing a thorough test suite—it needs constant attention and maintenance to keep running in top condition.

In Keep Your Ruby on Rails App Healthy, you'll learn about the tools and techniques for keeping your Ruby on Rails app running smoothly, and how to apply them to your apps.

The course delivers a range of practical and actionable lessons to enhance and protect your app right away, from simple, quick–win optimisations and setting up thorough monitoring to reviewing your site's performance, and checking your code against security vulnerabilities current best practices.

“I really enjoyed the book. A lot of quick wins for me to implement and makes me realise I can do more with guard.” –– Ben (@r0_0tKat)

Keep Your Ruby on Rails App Healthy is available as both an email course, and as a premium download edition.

The email course is split up into 7 lessons, delivered to your inbox over the course of a month.

The premium edition is available for instant download in PDF, ePub and Mobi (Kindle) format.

Start Email Course Buy Premium $9 (plus EU VAT)

rails howto programming
Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.