2
votes

I'm writing an app where I need to override the default routing helpers for a model. So if I have a model named Model, with the corresponding helper model_path() which generates "/model/[id]". I'd like to override that helper to generate "/something/[model.name]". I know I can do this in a view helper, but is there a way to override it at the routing level?

2

2 Answers

3
votes

You can define to_param on your model. It's return value is going to be used in generated URLs as the id.

class Thing
  def to_param
    name
  end
end

The you can adapt your routes to scope your resource like so

scope "/something" do
  resources :things
end

Alternatively, you could also use sub-resources is applicable.

Finally you need to adapt your controller as Thing.find(params[:id]) will not work obviously.

class ThingsController < ApplicationController
  def show
    @thing = Thing.where(:name => params[:id).first
  end
end

You probably want to make sure that the name of your Thing is unique as you will observe strange things if it is not.

To save the hassle from implementing all of this yourself, you might also be interested in friendly_id which gives you this and some additional behavior (e.g. for using generated slugs)

0
votes

You need the scope in routes.rb

scope "/something" do
  resources :models
end