Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Friendly-URLs in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 249
    Comment on it

    By default rails applications build URLs based on the primary key(id column) from the database. Suppose we have a User model and associated controller and we have a user record for John Martin that has id number 50. So the URL for his show page would be:

    /user/50

    The last segment of the url(50 here)is called the "slug". But if we want John's name in the URL instead of id.There are some ways to create better slugs.
    The simplest approach is to override the to_param method in the User model. Whenever we call a route helper,It will call to_param method to convert the object to a slug for the URL. If your model does not define the to_param method then Rails will use the implementation in ActiveRecord::Base, which just returns the id.
    So in the model, we will override to_param to include a parameterized version of the user's name:

    class User < ActiveRecord::Base
       def to_param
            "#{id}-#{name.parameterize}"
        end
    end

    In the example above the parameterize method from will convert any string into a URL.By adding content to the slug will improve SEO and make our URLs more readable
    Now wherever we call the route helper like this:

    user_path(@user)

    For our user John Martin with id number 50, the to_param method will generate a slug,and the full url would be:

    /user/50-Bob

    Now the the question arrises,what will happens in the show action of User controller.As params[:id] is the String of “2015-Hoverboard” and when we do User.find(params[:id]) the find method calls to_i. In Ruby when you call to_i on a String it grabs the first part of the String that looks like an integer.

    User.find("50-Bob")
    
    // Will be converted like this:
    
    User.find(50)

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: