Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic routes with Rails 3

I have a task to develop a rails application following the model for routing.

I need to have PageController and Page model. Page urls must be like /contacts, /shipping, /some_page.

Also i need have CatalogController and Category model. Categories urls must be like /laptops, /smartphones/android.

And it will be ProductsController and Product model, urls of products must be line /laptops/toshiba_sattelite_l605, /smartphones/android/htc_magic

I understand that this problem can be solved by using URLs like

  • /page/shipping
  • /catalog/smartphones/android

But the customer does not want to see the insertion of "/page" or "/catalog" in the URL.

Please tell me the direction for solving this problem. Sorry for my bad English.

like image 484
Beer Brother Avatar asked Nov 16 '10 15:11

Beer Brother


People also ask

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

How do I see all routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What are nested routes in Rails?

In a nested route, the belongs_to (child) association is always nested under the has_many (parent) association. The first step is to add the nested routes like so: In the above Rails router example, the 'index' and 'show' routes are the only nested routes listed (additional or other resources can be added).


1 Answers

You'll have to write a "catch-all" rule:

On routes.rb:

get '*my_precioussss' => 'sauron#one_action_to_rule_them_all'

Your precious controller:

class SauronController < ApplicationController
  def one_action_to_rule_them_all
    @element = find_by_slug(params[:my_precioussss])
    render @element.kind # product, category, etc
  end
end

Then you write one view for each "kind" of element: product.html.erb, category.html.erb, etc.

Make sure you write your find_by_slug implementation.

You can change one_action_to_rule_them_all to pikachu_i_choose_you and SauronController to PokemonController, will work too.

like image 84
Fábio Batista Avatar answered Oct 19 '22 05:10

Fábio Batista