Ruby on Rails: user friendly URLs

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


    To begin with, we put the rails of the latest version by executing in the console. gem install rails -v=3.1.3
    After the jam installation process is complete, create a new project with the team rails new nice_urls. As a result, we have a new clean project with all the jams installed, due to the fact that bundler was automatically launched at the end of the project generation.

    Post creation

    For demonstration, we will use ordinary scaffolding. Let's generate it for articles that have a title and text:
    rails g scaffold Post title:string text:text
    To make changes to the database, we will perform the migration command rake db:migrate. Now you can start the server (command rails s) and look at what we now have at the address. localhost:3000/posts
    We will see the familiar interface for adding posts:
    post scaffolding

    Beautiful links

    We go in app/views/posts/index.html.erband find the line that forms the link to show:
    <%= link_to 'Show', post %>
    Here postis the object that is used to form the path. It should be replaced with this design:
    post_path(:id => "#{}-#{post.title.parameterize}")
    To test the formation of links to the action show, 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


    Of course, the code on a real project will be different, turn into helpers and be called in a much more convenient form. Such a solution is not suitable everywhere and in some situations it will be extremely inconvenient. The likelihood of using the Cyrillic alphabet is also not taken into account here.

    Also popular now: