Adrian OPREA

February 19, 2022

Add slugs to Ruby on Rails models

There's only one word which describes the last 20 hours of working with Ruby on Rails: Stoked! 

It's my third day consistently working with Ruby on Rails and I'm in awe at the amount of things I got done while writing as little code as possible.

I decided to drop Next.js and move Remotium.io to Ruby on Rails. I kept trying to find tools to make my life easier in Next but it was getting too time consuming. I still love JavaScript and will probably continue making a living with it, but I want to be more mindful about the time investment required to work on personal projects.

Adding slugs with a unique ID

After moving all the models, porting some of the UI from Next, it was time to add slugs to job postings. I also wanted to mimic what I already knew: I needed a unique string appended to each slug, so that if jobs with similar titles were posted, they could all "exist"

Started with Google but also asked on Twitter. And, of course, Twitter was helpful — read the replies and you will learn why.

I am going to leave a list of all the links I used to add slugs (and unique IDs) to job postings. It's pointless detailing what I did, specifically, since everything is self-explanatory.

The goodies

I chose FriendlyId - the "Swiss Army bulldozer" of slugging and permalink plugins for Active Record because it was directly recommended to me on Twitter, by people I respect.

I enabled slug history, and I hit the following issue: Friendly_id preventing edit/new pages due to before_action :find_post. Here's the solution (elegant too).

I also looked at rsl/stringex before getting Twitter recommendations.

While looking for ways to generate a unique ID I landed here and ended up using what you see below:

image.jpeg


Enjoy & subscribe for more!