m_x
m_x

Reputation: 12564

Rails 3 routing : customize a resourceful route

I've got some Documents (and a DocumentsController), which are sorted using limited, fixed set of categories. I'd want my routes to take into account these categories, so my urls would look like :

/documents/:category/:id
/documents/:category/new
/documents/:category/:id/edit

...and so on, which should allow me to access params[:category] in order to filter the results. Is there a simple way to achieve this, that would still generate path helpers ? Or im i wrong to do this that way ?

Upvotes: 1

Views: 840

Answers (2)

Ben Simpson
Ben Simpson

Reputation: 4049

You can provide a path to a resource (as you mentioned):

# config/routes.rb
resources :documents, :path => 'documents/:category'

This would give you the following routes:

/documents/:category
/documents/:category/new
/documents/:category/:id/edit
/documents/:category/:id

I am not sure in this case what purpose the category capturing will serve, since you can reference the document by its primary key. This key most likely does not repeat across categories.

Upvotes: 2

joanwolk
joanwolk

Reputation: 1105

It's not hard to customize paths in Rails 3.

match '/documents/:id', to: 'documents#show', as: :document would give you the path helper document_path(:id). This will work even for an ID that's a string rather than a number, so extending this pattern to /documents/:category/:id/edit should be no problem.

Upvotes: 2

Related Questions