Using *_path and *_url functions with nested resources

Hi all,
I’ve been scouring the web trying to find an answer to this problem, but
most of the discussions I’ve found seem old, inconclusive or both.

I’m trying to create a resource(REST) based app that has users and
adverts posted to categories. I’d like to have my routes set up like
this:


map.resources :users do |users|
users.resources :adverts, :name_prefix => “users_”
end

map.resources :categories do | categories |
categories.resources :adverts, :name_prefix => “categories_”
end

Which would allow me to use URL like:
/users/1/adverts/new
/users/1/adverts/15;edit
/categories/35/adverts/84;edit

Which is all fine. However, in my adverts views, I need to generate the
paths to the actions in the correct parent resource. Obviously, I can’t
do something like user_advert_path(@user, @advert), as it will be
incorrect when I render the view from a category parent.

I know I could do a workaround by having a base route to /adverts
(map.resources :adverts) but, this seems to defeat some of the point of
using a REST structure in the first place. I’ve also seen people using
partials and passing in the name_prefix to them, but that seems pretty
inelegant to me (Restful polymorphic - Rails - Ruby-Forum)

I have to assume there must be a better way to generate the *path
functions, as this seems like a big open questions. Does anyone have any
advice?

Thanks,
Leslie

adverts_url(:user_id => 1) should generate

/user/1/adverts

adverts_url(:user_id => 1, :id => 99) should generate

/user/1/adverts/99

Use the same params for the *_path functions.

Regards,
John

On Mar 25, 9:20 pm, Leslie F. [email protected]

The thing about shared partials is that they are not supposed to make
assumptions and should be oblivious to their environment. That being
said. Having URLs in your partials violates this rule in my opinion. If
there is anyway to extract that environment specific information you
should. I encounter this problem all the time. I’ve done extremely
complex forms, with all kinds of AJAX calls, javascript, etc built in. I
then had to turn around and use this form in another part of my
application. Using the same partial seemed dirty and was not right. I
just copy and pasted the form in the other section. Redundancy in your
views is not that bad of a thing. In fact I think redundancy in your
controllers and views is perfectly fine if being DRY gets in the way of
flexibility.