1

使用多态嵌套资源时,我遇到了inherited_resources 的问题,其父资源之一是命名空间控制器。这是一个抽象的例子:

# routes.rb
resources :tasks do
  resources :comments
end   
namespace :admin do
  resources :projects do
    resources :comments
  end
end

# comments_controller.rb
class CommentsController < InheritedResources::Base
  belongs_to :projects, :tasks, :polymorphic => true
end

当我访问/admin/projects/1/comments时,我收到此错误:

ActionController::RoutingError at /admin/projects/1/comments
uninitialized constant Admin::CommentsController

Admin::CommentsController现在如果我定义控制器controllers/admin/tasks/1/comments

有没有办法解决这个问题?

4

2 回答 2

1

为什么不保留CommentsController它的位置并为管理员创建一个单独的控制器来admin/comments_controller.rb?继承它呢?

class Admin::CommentsController < CommentsController
   before_filter :do_some_admin_verification_stuff

  # since we're inheriting from CommentsController you'll be using
  # CommentsController's actions by default -  if you want
  # you can override them here with admin-specific stuff

protected
  def do_some_admin_verification_stuff
    # here you can check that your logged in used is indeed an admin,
    # otherwise you can redirect them somewhere safe.
  end
end
于 2013-12-18T11:24:04.393 回答
0

Rails Guide中提到了对您问题的简短回答。

基本上你必须告诉路由映射器使用哪个控制器,因为默认值不存在:

#routes.rb
namespace :admin do
  resources :projects do
    resources :comments, controller: 'comments'
  end
end

这将解决您的路由问题,这实际上可能与Inherited Resources.

另一方面,Inherited Resources在命名空间内嵌套控制器的情况下,我也无法使用。因为这个,我离开了那颗宝石。

我创建了一些你可能会感兴趣的东西:一个控制器关注点,它将定义继承资源提供的所有有用的路由助手,以一种考虑命名空间的方式。它不够聪明,无法处理可选的或多重的亲子关系,但它让我省去了很多输入长方法名的麻烦。

class Manage::UsersController < ApplicationController
  include RouteHelpers
  layout "manage"
  before_action :authenticate_admin!
  before_action :load_parent
  before_action :load_resource, only: [:show, :edit, :update, :destroy]
  respond_to :html, :js

  create_resource_helpers :manage, ::Account, ::User

  def index
    @users = parent.users
    respond_with [:manage, parent, @users]
  end

  def show
    respond_with resource_params
  end

  def new
    @user = parent.users.build
    respond_with resource_params
  end
  #  etc...
end

然后在我的观点中:

    td = link_to 'Show', resource_path(user)
    td = link_to 'Edit', edit_resource_path(user)
    td = link_to 'Destroy', resource_path(user), data: {:confirm => 'Are you sure?'}, :method => :delete

希望有帮助!

于 2014-05-15T21:43:33.723 回答