SEO slugs for Rails


Published: September 01, 2015

Category: SEO Tips

One of the essential SEO improvements you can make to any web application is to ensure database related URLs are not represented by id numbers.


Instead of:
http://my-site/products/5
we need to have:
http://my-site/products/fridge-freezer-magnets

In this short article we show you how to achieve this without the use of plugins ( gems or packages ) for Ruby on Rails. In this example we will assume an existing Product model and controller, with "name" and "id" attributes.

In Rails

Step 1: Create a "slug" column in the model with terminal command:

rails generate migration add_slug_to_products slug:string
rake db:migrate

Validate uniqueness of the name attribute, add a before hook and to_param method to the Product model

validates :name, presence: true, length: { minimum:5,maximum: 70 },
	uniqueness: true, format: { with: /\A[a-zA-Z\s]+\z/,
    message: "only allows letters" }

before_create do self.slug = name.downcase.gsub(" ", "-") end
def to_param slug end

In the controller responsible for the Product model ( usually ProductsController ) alter the methods as below, and add "slug" to product_params

def index
  @products=Product.all
end

def new
  @product=Product.new
end

def create
  @product=Product.new(product_params)
  ...
  ...
end

def show
  @product=Product.find_by_slug(params[:id])
end

def edit
  @product=Product.find_by_slug(params[:id])
end

def update
  @product=Product.find_by_slug(params[:id])
  ...
  ...
end

def destroy
  @product=Product.find_by_slug(params[:id])
  ...
  ...
end

private
  def product_params
     params.require(:product).permit(:name, :slug)
  end

In your index view, you can create a link to the the product show page by referencing the slug:

@products.each do |x|
  <%= link_to(product_path(x.slug)) do %>
    <%= x.name %> 
    <% end %>
  <% end %>

Back to News

GET SEO NEWS AND UPDATES SENT DIRECTLY TO YOUR INBOX. SIGN UP TO OUR NEWSLETTER

No Thanks, I have enough traffic already!


google certified SEO agency
Copyright ©2017 8Ball DigitalTM 163 Treffry Rd, Truro, Cornwall TR1 1UF