ruby-on-rails - rails 3 : Getting the ID of a Namespaced Model

标签 ruby-on-rails routing namespaces

我有一个模型叫 Contributor ,它还充当其他几个模型的命名空间,例如 Contributor::AliasContributor::Reassignment .我想使用一个包含贡献者 ID 的 URL,如下所示:

/contributors/1/reassignments/new

但我收到此错误:
No route matches [GET] "/contributors/1/reassignments/new"

我的 routes.rb文件包括:
namespace :contributor do
  resources :reassignments
end
resources :contributors

我也试过:
resources :contributors do
  resources :reassignments
end

这会导致不同的错误:
uninitialized constant ReassignmentsController

知道如何解决这个问题吗?也许我不应该使用也充当模型的命名空间?我还没有在任何教程中看到这样做过,尽管它似乎是可能的。

更新:

您如何处理深度嵌套的命名空间模型,例如:
resources :contributors do
  resources :reassignments, :module => "contributor" do
    resources :approvals, :module => "reassignment"
  end
end

使用这种方法,我得到错误:
No route matches {:action=>"create", :controller=>"contributor/reassignment/approvals"}

我的 Controller 目录确实具有以下结构:
contributor ->
  reassignment ->
    approvals_controller.rb

这似乎与第一个错误有关,但也许是新的东西。

最佳答案

不清楚您是否有贡献者资源。如果你这样做了,你的routes.rb中的以下内容:

resources :contributors do
  resources :reassignments, :module => "contributor"
end

如果没有,请尝试:
resources :reassignments, :module => "contributor", :path => "/contributors/:contributor_id/reassignments"

请注意,在第二种情况下,您需要构造一个 url 并在调用 link_to、form_for 和类似位置时显式地将 :contributor_id 传递给它。

如果你想在那里使用 [@contributor,@reassignment] 格式,你最好坚持第一种方法,你有一个贡献者资源。

更新:对于三级嵌套,如果您的 Controller 目录也没有与资源并行嵌套,您可以明确指定 Controller ,例如:
resources :contributors do
  resources :reassignments, :controller => "contributor/reassignments" do
    resources :approvals, :controller => "reassignment/approvals"
  end
end  

但是,请不要那样做。 Rails 不鼓励使用 3 级和更多级嵌套。在此处查看推荐的内容:http://weblog.jamisbuck.org/2007/2/5/nesting-resources

关于ruby-on-rails - rails 3 : Getting the ID of a Namespaced Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15125922/

相关文章:

ruby-on-rails - 无法连接到数据库 - 无法将 PostgreSQL 数据库推送到 heroku

php - Zend Framework 2 段路由需要段

ruby-on-rails - Rails 中同一路由的 POST 和 GET 请求的不同 Controller 操作

JavaScript 命名空间模式

python - 脚本之间的全局变量

ruby-on-rails - 验证是否存在送货地址,除非它与账单地址相同

ruby-on-rails - 无法在 ActionMailer 中呈现内联附件

css - 960px 宽度响应式 Bootstrap 容器 rails 应用程序

android - 移动网状网络为Android分享互联网连接

c# - 如何确定命名空间位于哪个程序集中?