Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

polymorphic_url generates wrong URL for namespaced nested resources #10705

Closed
miharekar opened this issue May 21, 2013 · 2 comments
Closed

polymorphic_url generates wrong URL for namespaced nested resources #10705

miharekar opened this issue May 21, 2013 · 2 comments

Comments

@miharekar
Copy link
Contributor

I wrote this to heartcombo/simple_form#805 but we figured simple_form just uses polymorphic_url to generate URLs, so the problem must be there. I'm using Rails 4 rc 1.

I have Galleries with nested Photos and both namespaced under Admin

  namespace :admin do
    resources :galleries do
      resources :photos
    end
  end

So when I do
simple_form_for [@admin_gallery, @admin_photo]
I get undefined method 'admin_gallery_admin_photos_path'.

If I do simple_form_for [:admin, @admin_gallery, @admin_photo]
I get undefined method 'admin_admin_gallery_admin_photo_path'.

I got it to work by giving the simple_form the direct url like so: url: admin_gallery_photo_path(@admin_gallery, @admin_photo)
but that isn't pretty, and polymorphic_url should probably handle that better 😃

@josevalim
Copy link
Contributor

If your model is namespaced, the model name will indeed be admin_gallery and the error undefined method 'admin_admin_gallery_admin_photo_path' is actually correct.

There is a disconnection in between how you are naming your routes and the names you are giving to your model. The namespace :admin call in your router doesn't imply the model name should be namespaced. Notice polymorphic_url heuristic is very simple, it simply gets the model names, put them together and attempt to generate a URL.

That said, there are two ways you could solve your problem:

  1. Use as: :admin_gallery and as: :admin_photo on your resources call

  2. In app/models/admin.rb, add this:

module Admin
  def self.use_relative_model_naming?
    true
  end
end

I haven't tried this approach directly yet but this will tell Rails that you want the model Admin::Gallery to be treated as Gallery. So the generated route won't include the admin_ nor the parameter name (you will use params[:gallery] instead of params[:admin_gallery] in your controller too).

@miharekar
Copy link
Contributor Author

Thanks a lot. I'll look into that 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants