我有一个属于Bar的嵌套资源Foo。我可以成功列出所有属于任何给定BarFoo对象。但我也希望能够从它们所属的任何Bar对象生成一个列出了所有Foo项的 View 。

模型结构为:

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

# app/models/bar.rb
class Bar < ActiveRecord
  belongs_to :foo
end

路由定义为:
# config/routes.rb
resources :foos do
  resources :bars
end

我从此配置中获得了预期的路由:
   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

我需要为bars#index生成一条不在foo上下文内的路由。换句话说,我本质上是想要:
bars  GET    /bars(.:format)      bars#index

我试过使用浅选项,因此:
# config/routes.rb
resources :foos, shallow: true do
  resources :bars
end

但是,根据documentation,这不支持:index操作。

最好的方法是什么?有一个有用的Stack Overflow讨论here,使用before_filter确定范围-但这是从2009年开始的。感谢有关如何正确设置 Controller 和config/routes.rb文件的任何具体指导!

最佳答案

如果要保留范围索引方法foo_bars和单独的bars路由/ View ,请执行以下操作:

routes.rb中创建一个自定义路由:

get 'bars' => 'bars#index', as: :bars

如您的链接中所述,在bars Controller 中设置索引方法,或者简单地:
def index
  if params[:foo_id]
    @bars = Foo.find(params[:foo_id]).bars
  else
    @bars = Bar.all
  end
end

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

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

routes.rb中创建一个自定义路由:
get 'bars' => 'bars#index', as: :bars

编辑现有路线以排除嵌套索引:
resources :foos do
  resources :bars, except: :index
end

然后bars Controller 可能只是:
def index
  @bars = Bar.all
end

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

关于ruby-on-rails-4 - Rails 4-如何为嵌套资源添加索引路由,以便列出独立于父资源的所有项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31757006/

10-11 16:21