Replace URL params with a string

Hey,

First, I have seen some similar issues but none of the answers are clear.

I am trying to achieve replacing the route that is served via id params.

Currently, you can simply reach every post via /post/1, which I am trying to replace with /post/post-name.

In other words, I don’t want to show my post’s id on the browser to avoid exposing id field.

Could you please let me know how can I achieve this?

Thanks.

The best way is to use gem friendly_id. You can do it without this gem, but there’s a higher chance to screw something, if you don’t know what you are doing.

I suggest you to read this page on stackoverflow.

I was not thinking to use a gem for this workaround but still, thank you for your help

IMO, you can create a db migration to either add a new column or a whole new table referencing to the original one and store a friendly id from the title of the post. You must keep that as index and never allow duplicate items. Whenever a duplicate item is stored, you should handle that with a counter (like hello-world, hello-world1, etc.).

Now in the routes, you still use :id/ but you send the title of the article (or whatever) instead. Handle that from your controller to find the item by the unique title instead of id.

That’s just it… I will suggest you to use friendly_id gem if you’re in rush or building a prototype. But if you DIY, it will be better and give you fine control over everything for sure.

1 Like