Rails 4 - 如何为嵌套资源添加索引路由,以便列出独立于父资源的所有项目

Scr*_*cro 7 nested-attributes nested-routes ruby-on-rails-4

我有一个Bar属于的嵌套资源Foo.我可以成功列出Bar属于任何给定的所有对象Foo.但我也希望能够生成一个视图,其中包含所有Bar项目,无论Foo它们属于哪个对象.

模型结构是:

# app/models/foo.rb
class Foo < ActiveRecord
  has_many :bars
end

# app/models/bar.rb
class Bar < ActiveRecord
  belongs_to :foo
end
Run Code Online (Sandbox Code Playgroud)

路由定义为:

# config/routes.rb
resources :foos do
  resources :bars
end
Run Code Online (Sandbox Code Playgroud)

我从这个配置中获得了预期的路由:

   foo_bars GET    /foos/:foo_id/bars(.:format)      bars#index
            POST   /foos/:foo_id/bars(.:format)      bars#create
new_foo_bar GET    /foos/:foo_id/bars/new(.:format)  bars#new
   edit_bar GET    /bars/:id/edit(.:format)          bars#edit
        bar GET    /bars/:id(.:format)               bars#show
            PATCH  /bars/:id(.:format)               bars#update
            PUT    /bars/:id(.:format)               bars#update
            DELETE /bars/:id(.:format)               bars#destroy
       foos GET    /foos(.:format)                   foos#index
            POST   /foos(.:format)                   foos#create
    new_foo GET    /foos/new(.:format)               foos#new
   edit_foo GET    /foos/:id/edit(.:format)          foos#edit
        foo GET    /foos/:id(.:format)               foos#show
            PATCH  /foos/:id(.:format)               foos#update
            PUT    /foos/:id(.:format)               foos#update
            DELETE /foos/:id(.:format)               foos#destroy
Run Code Online (Sandbox Code Playgroud)

我需要的是生成一个路径,bars#index该路线不在上下文范围内foo.换句话说,我基本上想要:

bars  GET    /bars(.:format)      bars#index
Run Code Online (Sandbox Code Playgroud)

我尝试过使用浅选项,因此:

# config/routes.rb
resources :foos, shallow: true do
  resources :bars
end
Run Code Online (Sandbox Code Playgroud)

但是,根据文档,这不支持:index操作.

最好的方法是什么?有一个有益的堆栈溢出讨论这里,用before_filter确定的范围-但它从2009年的欣赏就如何设置控制器和两个任何具体的指导config/routes.rb适当的文件!

Jos*_*eph 5

如果要保留范围索引方法foo_bars和单独的bars路径/视图:

创建自定义路线routes.rb:

get 'bars' => 'bars#index', as: :bars
Run Code Online (Sandbox Code Playgroud)

bars按照链接中的说明在控制器中设置索引方法,或者只是:

def index
  if params[:foo_id]
    @bars = Foo.find(params[:foo_id]).bars
  else
    @bars = Bar.all
  end
end
Run Code Online (Sandbox Code Playgroud)

然后创建一个bars视图目录(如果你没有)和index.html.erb.


如果您不想保留范围索引方法foo_bars:

创建自定义路线routes.rb:

get 'bars' => 'bars#index', as: :bars
Run Code Online (Sandbox Code Playgroud)

编辑现有路由以排除嵌套索引:

resources :foos do
  resources :bars, except: :index
end
Run Code Online (Sandbox Code Playgroud)

然后bars控制器可能只是:

def index
  @bars = Bar.all
end
Run Code Online (Sandbox Code Playgroud)

然后创建一个bars视图目录(如果你没有)和index.html.erb.