Skip to content

Instantly share code, notes, and snippets.

@r3cha
Last active April 6, 2019 20:54
Show Gist options
  • Save r3cha/ce2c31603da469b7d0ca2d9fcaac1a38 to your computer and use it in GitHub Desktop.
Save r3cha/ce2c31603da469b7d0ca2d9fcaac1a38 to your computer and use it in GitHub Desktop.
How to generate friendly urls without overhead of friendly id and etc.
# db/migrate/create_items.rb
# if you use activerecord
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :title
t.string :slug
t.timestamps
end
end
end
# app/model/concerns/generate_slug.rb
module GenerateSlug
extend ActiveSupport::Concern
included do
before_save do
self.slug = generate_slug if self.slug.blank?
end
end
def generate_slug
# you should convert you title that can be with spaces to something more acceptable for urls
# you can chage it as you need for your specific language situation
slug = transliterate(self.title).parameterize
#add id as prefix if you have record with same titel aleady
"#{self.id}-#{slug}" if self.class.find_by(slug: slug).present?
end
end
# app/models/item.rb
class Item < ApplicationRecord
# or if you use mongoid
# class Item
# inclide Mongoid::Document
include GenerateSlug
end
# config/routes.rb
Rails.application.routes.draw do
#....
# param: :slug mean here that instead for passing param called id we pass param called slug
# can check it with rake routes
resources :items, only: [:index, :show], param: :slug
#....
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment