📜 ⬆️ ⬇️

Ruby on Rails: user friendly URLs

This article will show an example of how to make beautiful links in a Rails project. Links of the form /posts/1/ will be converted to /posts/1-article-name/

Training

Let's start with the fact that we put the rails of the latest version by running gem install rails -v=3.1.3 in the console
After the process of installing the jam, create a new project with the team rails new nice_urls . As a result, we have a new clean project with all the installed jams, due to the fact that at the end of the project generation a bundler was automatically launched.

Creating posts

For demonstration, the usual scutolding will suit us. Let's generate it for articles that will have a title and text:
rails g scaffold Post title:string text:text
To make changes to the database, run the migration command rake db:migrate . Now you can start the server ( rails s command) and look at what we currently have at localhost:3000/posts
You will see the familiar interface for adding posts:
post scaffolding
')
Beautiful links

Go to app/views/posts/index.html.erb and find the line that forms the link to the show :
<%= link_to 'Show', post %>
Here post is an object that is used when forming the path. It should be replaced with this design:
post_path(:id => "#{post.id}-#{post.title.parameterize}")
To test the formation of links to show action, you need to add at least one article, which will be given a title. Let's use the interface to create posts and call it “The test of nice urls”. After creating posts in the listing, the link should no longer lead to /posts/1 , but to /posts/1-the-test-of-nice-urls

Conclusion

Of course, the code on a real project will be different, turn into helper and called in a much more convenient form. Such a solution is not suitable everywhere, and in some situations it will be extremely inconvenient. It also does not take into account the possibility of using Cyrillic

Source: https://habr.com/ru/post/133627/


All Articles