Last active
April 6, 2019 20:54
-
-
Save r3cha/ce2c31603da469b7d0ca2d9fcaac1a38 to your computer and use it in GitHub Desktop.
How to generate friendly urls without overhead of friendly id and etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/item.rb | |
class Item < ApplicationRecord | |
# or if you use mongoid | |
# class Item | |
# inclide Mongoid::Document | |
include GenerateSlug | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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