[ rails ] friendly_id

What is friendly_id ?

With FriendlyId, it’s easy to make your application use URLs like:

http://example.com/states/washington

instead of:

http://example.com/states/4323454

 

class User < ApplicationRecord
include FriendlyId
friendly_id :name, use: :slugged
end

User.create! name: "Joe Schmoe"

# Change User.find to User.friendly.find in your controller
User.friendly.find(params[:id])

use: :slugged = look for a slug column in the database’s articles table

Unique Slugs by Scope

Generate unique slugs within a scope.

Example

two restaurants in different cities to have the slug
+joes-diner+.
Please do note that you must drop the uniqueness constraint on the slug’s
column in the database when you’re scoping the slug.

class Restaurant < ActiveRecord::Base
extend FriendlyId
belongs_to :city
friendly_id :name, :use => :scoped, :scope => :city
end

class City < ActiveRecord::Base
extend FriendlyId
has_many :restaurants
friendly_id :name, :use => :slugged
end

City.friendly.find("seattle").restaurants.friendly.find("joes-diner")
City.friendly.find("chicago").restaurants.friendly.find("joes-diner")

Without :scoped in this case, one of the restaurants would have the slug joes-diner and the other would have joes-diner-f9f3789a-daec-4156-af1d-fab81aa16ee5.

class Cuisine < ActiveRecord::Base
extend FriendlyId
has_many :restaurants
friendly_id :name, :use => :slugged
end

class City < ActiveRecord::Base
extend FriendlyId
has_many :restaurants
friendly_id :name, :use => :slugged
end

class Restaurant < ActiveRecord::Base
extend FriendlyId
belongs_to :city
friendly_id :name, :use => :scoped, :scope => [:city, :cuisine]
end

ref : http://norman.github.io/friendly_id/file.Guide.html, https://github.com/norman/friendly_id#rails-quickstart,

http://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast,

http://ruby.zigzo.com/2011/10/08/how-to-use-the-friendly_id-gem-w-sti-models/,

https://github.com/norman/friendly_id/issues/167

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s