How to Change URLs in Rails

I have a resource called Book, then I have domains such as:

   domain.com/books/272

But I want to change it to

   domain.com/stories/272

For URL only, no need to change controller, classes, etc.

In the routes I have

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

  map.root :controller => 'static'

How can i do this? Thanks

+5
source share
3 answers

Depends on what you already have.

#resource routes
map.resources :books, :as => :stories
#named routes
map.books 'stories/:id'

Without defining routes, the only option I can think of — which seems terribly wrong — is to add a new controller that inherits from your book controller. You will need to go through your application and change the name of the controller used to generate paths or URLs.

class BooksController < ApplicationController

class StoriesController < BooksController

, , , .

http://guides.rubyonrails.org/routing.html

+4

rails 3, , :

resources :books, :path => 'stories'
+5

config/routes.rb

:

map.stories 'stories/:id', :controller => 'books', :action => 'show'

:

<%= link_to book.name, stories_path(book) %>

, book.name , . , book .

:id, SEO to_param .

:

 def to_param
     "#{id}-#{name.gsub(/\s/, '_').gsub(/[^\w-]/, '').downcase}"
 end

Also, make sure you replace namewith the attribute that the book model actually has.

+3
source

All Articles