Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change URL in Rails

I have a resource called Book, then I have domains like:

   domain.com/books/272

But I want to change it to

   domain.com/stories/272

Only for the URL, don't 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 it? Thanks

like image 356
Victor Avatar asked Aug 20 '10 23:08

Victor


People also ask

How do I get the URL in Ruby?

You can write request. url instead of request. request_uri . This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

What is the best way to get the current request URL in Rails?

What is the best way to get the current request URL in Rails? You should use request. original_url to get the current URL.

How do I find the path in Rails?

To solve this, you'll need to use a built-in Rails helper called current_page? . With the current_page? helper you can pass it things like a relative or absolute path that you'd like to check or you can even pass it actions and controllers with parameters for it to check. Doing so will return either a true or false .


2 Answers

In rails 3, I believe you would do the following:

resources :books, :path => 'stories'
like image 73
Muhd Avatar answered Sep 20 '22 15:09

Muhd


Depends really on what you have already.

Use this code to your routes file: (in the case of the original URL of books replaced by stories)

#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 which inherits from your books controller. You'd need to go through your application and change the controller name used to generate paths or URLs as seen in the following example:

class BooksController < ApplicationController

class StoriesController < BooksController

Personally, I would recommend you take the time to define your routes but I guess this depends on how large an application you're working with.

This guide will help you understand routing in RoR: http://guides.rubyonrails.org/routing.html

like image 43
mark Avatar answered Sep 18 '22 15:09

mark