[英]Rails url_for namespaced models and non-namespaced controller
I'm trying to generate a URL for a model which is namespaced from a controller which is not. 我正在尝试为不是从控制器命名空间的模型生成URL。 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. 问题是Rails希望存在一个“ some_stuff_widget_path”,但这并不是因为控制器没有命名空间。 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. 我尝试了另一篇文章(http://stackoverflow.com/questions/4404440/rails-url-for-and-namespaced-models)中提供的解决方案,但它们似乎没有用。
My models are technically in a separate gem which is namespaced and then my Rails app includes that gem and provides controllers. 从技术上讲,我的模型位于一个单独的带有命名空间的gem中,然后我的Rails应用程序包括该gem并提供控制器。 Without changing that setup, is there a way to get "url_for" to work? 在不更改该设置的情况下,是否有办法使“ url_for”正常工作?
As mentioned in one of your comments above, you have 正如您在上面的评论之一中提到的,
resources :widgets
in your config/routes.rb
. 在您的config/routes.rb
。 In the location
you're trying to set above with the url_for
, you're trying to match the following route 在您尝试使用url_for
在上方设置的location
,您尝试匹配以下路线
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. 但是正如您所说, url_for w
导致Rails猜测您正在寻找(不存在的) some_stuff_widget_path
路由。 Instead change that line to 而是将该行更改为
location = url_for widget_path(w)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.