Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Adding slugs to ActiveRecord models in Rails

21 Oct 2023 Here’s how to implement a Sluggable module that turns an ActiveRecord model into one with a user-defined slug for nice page identifiers.The basic idea of this module is that you’ll be able to find the said record with a slug in the URL and at the same time use path helpers by passing models as usual:To have slug in the URL instead of the id, we can tell Rails router the default param is slug instead of an id:This works, but you still need to pass the slug parameter explicitely in the path helper:Not so pretty.But redefining to_param on a model fixes this:Now that we know how paths work, we can implement a general Sluggable module for user-defined slugs:This is a regular model concern that works with a previously added slug column on a model, but one important thing to realize is that you need to be careful about allowing users to choose restricted paths.You need to avoid controller’s actions and perhaps some extra paths on top.To this end we’ll define RestrictedPathsValidator:Finally, here are some tests you can add to a model implementing slugs including ones checking the controller methods:And that’s really it. The model id stayed in tact, so nothing else has to change in your application. Learn the ins and outs of web application deployment with Ruby, Python, and Linux. More → Save 100+ hours and forget international tax on your next Ruby on Rails business idea. More →



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Adding slugs to ActiveRecord models in Rails

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×