Mapping resources twice?

Named changed to protect the innocent.

So I have

map.resources :stories do |story|
story.resources :comments
end

This lets me have /story/1/comments or /story/1/comment/3.

If I want to still have access to plain old /comments to give me all
comments across all stories do I need to have:

map.resources :comments

map.resources :stories do |story|
story.resources :comments
end

Is this allowed ? Can I map the same resource into two different
contexts ?

Alan

map.resources :comments
map.resources :stories do |story|
story.resources :comments, :name_prefix => “inner_”
end

Now you’ll have:

comment_url(@comment)
inner_comment_url(@story, @comment)

Hi David,

That looks like it’ll fit the bill perfectly.

map.resources :comments, :name_prefix => “all_”

map.resources :stories do |story|
story.resources :comments, :name_prefix => “story_”
end

Giving me all_comments_url (not likely to use singular here) and
story_comment_url(@story, @comment)

Sweet.

Alan

Hi –

On Mon, 27 Nov 2006, Alan F. wrote:

This lets me have /story/1/comments or /story/1/comment/3.

Is this allowed ? Can I map the same resource into two different
contexts ?

The thing is, when you call resources, you create methods called
comments_url, comment_url, etc. So if you create those methods twice,
the second set take precedence.

There are a couple of things you can do. One is [untested so tweak if
I’ve mistyped it]:

map.resources :comments
map.resources :stories do |story|
story.resources :comments, :name_prefix => “inner_”
end

Now you’ll have:

comment_url(@comment)
inner_comment_url(@story, @comment)

You can also add the :name_prefix to the plain comments resources, if
you’d rather have it work that way.

Another thing you can do – but be warned; it’s very experimental, and
also may or may not suit your schema – is use my Inferred Routes
plugin. This allows you to do just the nested route, and then when
you do:

comment_url(@comment)

the plugin will infer:

comment_url(@comment.story, @comment)

You can get the plugin at:
http://www.risleydale.net/svn/inferred_routes/tags/0.1.1

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs