Karl
Karl

Reputation: 6165

Double-nested Routing

Currently I have Steps which belong to Procedures:

map.resources :procedures, :has_many => :steps

And this works fine for me, I get URLs that look like /procedures/3/steps/5.

However, suppose I wanted to add one more layer, Figures that belong to steps, to get this: /procedures/3/steps/5/figures/1

That being a monster of a URL aside, how exactly would I do the routing for this?

Edit: Maybe I shouldn't put that aside, should I do this? Figures are simply containers for images which I will display in the Steps, so it's not like the user will actually "visit" any Figure, I just need to fetch the images from the Figures.

Upvotes: 0

Views: 661

Answers (3)

askegg
askegg

Reputation: 664

map.resources :procedures do |procedure|
  procedure.resources :steps do |step|
    step.resources :figures
  end
end

If you need routes like /figures/ then use:

map.resources :procedures, :shallow => true do |procedure|
  procedure.resources :steps do |step|
    step.resources :figures
  end
end

In your views it's something like:

<%= link_to "Figure", figure_url(@procedure, @step, @figure) -%>

Upvotes: 2

mylescarrick
mylescarrick

Reputation: 1680

From your comment, I think you're right: you won't ever need to route to the figures... and you never want to unnecessarily over-complicate your routes.

It sounds like the furthest you'll go will be the Show action for your steps... and you'll just ask ActiveRecord for the list of figures for that step. That is, you'll have

class Step < ActiveRecord::Base
  has_many :figures
end

and

class Figure < ActiveRecord::Base
  belongs_to :step
  has_many :images #perhaps?
end

but for routing you only need to care about resources that will be RESTfully requested - in this case it looks like your procedures, and their associated steps. The route you listed in the question looks spot-on to me!

Upvotes: 1

dbrown0708
dbrown0708

Reputation: 4754

This blog post explains it better than I can off the top of my head. Basically, you can use the :name_prefix option when defining your routes to acheive what you're looking for.

Upvotes: 1

Related Questions