0

I'm trying to generate a URL for a model which is namespaced from a controller which is not. For example:

module SomeStuff
  class Widget < ActiveRecord::Base; end
end

class WidgetsController < ApplicationController
  def create
    w = Widget.create(params)
    location = url_for w
    render :json => w, :location => location
  end
end

The problem is Rails wants a "some_stuff_widget_path" to exist and it doesn't because the controller is not namespaced. I tried the solutions given in another post (http://stackoverflow.com/questions/4404440/rails-url-for-and-namespaced-models) but they didn't seem to work.

My models are technically in a separate gem which is namespaced and then my Rails app includes that gem and provides controllers. Without changing that setup, is there a way to get "url_for" to work?

codecraig
  • 3,118
  • 9
  • 48
  • 62
  • Why not run `rake routes` to find the method name for the route you're trying to link to in the above `url_for` and pass `w` to it? – deefour Jul 09 '12 at 14:38
  • rake routes doesn't tell me the method, however, Rails gives me the error that it's trying to call "some_stuff_widget_path" on the controller, but the controller doesn't have that method b/c the controller is not namespaced. – codecraig Jul 09 '12 at 15:12
  • `rake routes` will tell you all routes in your application. By just passing `w`, you're asking rails to guess the method for the route you're trying to use. It's incorrectly guessing `some_stuff_widget_path` because of the namespacing situation you're in, so I am suggesting you look through the list of routes `rake routes` generates to find the correct method path. If no such method exists, you have not defined any route to match the path you're after, and must do so in `config/routes.rb`. – deefour Jul 09 '12 at 15:35
  • I think I understand. I currently have `resources :widgets` in my config/routes.rb, so it seems I need to have some additional routes to make this work. – codecraig Jul 09 '12 at 15:59

1 Answers1

1

As mentioned in one of your comments above, you have

resources :widgets

in your config/routes.rb. In the location you're trying to set above with the url_for, you're trying to match the following route

widget GET    /widgets/:id(.:format)    widgets#show

But as you said, url_for w is instead causing rails to guess you're looking for the (non-existent) some_stuff_widget_path route. Instead change that line to

location = url_for widget_path(w)
deefour
  • 34,974
  • 7
  • 97
  • 90
  • specifically: location = url_for widget_url(w) – codecraig Jul 09 '12 at 17:24
  • This approach won't work if you're going to use `form_for` helpers where you pass class instances to generate url. [Linked question](http://stackoverflow.com/questions/4404440/rails-url-for-and-namespaced-models?lq=1) has better approach. – olhor Dec 13 '14 at 12:53
  • This is one reason `form_for` supports a `:url` option. `form_for @w, url: widget_path(@w)` – deefour Dec 13 '14 at 14:36