Search code examples
ruby-on-railsrubyruby-on-rails-3clean-urls

Clean url with rails


I can't use any of the gems for creating clean Urls in rails. Instead I am rolling out my own implementation. I have created the following entry in routes.rb

match "/:slug" => "cleanurls#index"

Where cleanurl is a controller for handling all such requests. In the cleanurl controller:

class CleanurlsController < ApplicationController


 def index

  slug  = params['slug']

  url = Url.where(:slug => slug).first

  case(url.url_type) 

       when 'profile'

                 user_id = url.id.to_i
                 @profile = Profile_info.getProfileDetails(user_id)
                 render '/profiles/index'
       end

 end

end

I have created the table urls which stores the slug,id (as relevant) and the type of page. Right now I have only the profile page to deal with but in the future I will have different types of pages with clean urls.

My first Question:

1) Is this implementation the right approach? And is this okay from a performance perspective given the tables have all the right indexes.

I am making the profile url like this:

    def self.makeProfileUrl(id,name)

     name = name.strip.titleize

     extension = User.where(:name => name).count - 1

     slug = name.split(" ").join("-")

     if extension != 0
        slug += "-#{extension}"
     end

        Url.create(:slug => slug, :id => id.to_i, :url_type => 'profile')

   end

I am using extension to append a count in case their are users who share the same name.

Question:

Is this the right way to create the slug and ensure it being unique? Fetching the count of a name from the other table does not seem right.


Solution

  • Answering the question #1:

    I don't know the details of what's your overall goal, but if you'd like to have such URLs that are based on records from the database - then yes: it's a good approach.

    Answering question #2 (regarding slugs):

    I'd rather use something much more elaborate and well tested like: https://github.com/norman/friendly_id

    My 50 cents about some other things:

    Is this one of your first projects in Ruby/Rails? If so - congratulations! :) I'm asking because I noticed that you're using camel case here and there...

    Also:

    user_id = url.id.to_i
    

    Why do you call this #to_i method here? Did you set up this id as a string or something?

    Hope this helps