Creating Friendly Rails URLs

I have a slightly different attitude towards a fairly common problem: SEO-friendly URL. I have a PagesController, so my urls are currently similar (using calm routing):

/ pages / some-content in title

This works fine, but there is a hierarchical structure for the pages, so I need the following:

/ some-content-title routes to / pages / some -content-title

I can also get this using:

match '*a', :to => 'errors#routing'

in my .rb routes and catching it in ErrorsController as:

class ErrorsController < ApplicationController
  def routing
    Rails.logger.debug "routing error caught looking up #{params[:a]}"
    if p = Page.find_by_slug(params[:a])
      redirect_to(:controller => 'pages', :action => 'show', :id => p)
      return
    end
    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end
end

My question is the desired elimination of the "part of the page /" URL. What the SEO dude wants (and here's an example):

/ insurance =>: controller => 'pages' ,: id => 'insurance' #, but the address in the address bar is insurance

/insurance/car: controller = > 'pages',: category = > 'insurance',: id = > 'car' #, -//

Google , ?

!

+3
2

, , ( ) . globbed , URL-, , .

Rails 3 Rack . ( ) . :

class SeoDispatcher
  AD_KEY = "action_dispatch.request.path_parameters"

  def self.call(env)
    seopath = env[AD_KEY][:seopath]
    if seopath
      param1, param2 = seopath.split("/") # TODO handle paths with 3+ elements
      if param2.nil?
        env[AD_KEY][:id] = param1
      else
        env[AD_KEY][:category] = param1
        env[AD_KEY][:id] = param2
      end
    end
    PagesController.action(:show).call(env)
    # TODO error handling for invalid paths
  end
end
#

MyApp::Application.routes.draw do
  match '*seopath' => SeoDispatcher
end

:

GET '/insurance'     => PagesController#show, :id => 'insurance'
GET '/insurance/car' => PagesController#show, :id => 'car', :category => 'insurance

URL- , .

+5

friendly_id. . github

0

Source: https://habr.com/ru/post/1793714/


All Articles