Ruby on rails 4 Rails 4-如何为嵌套资源添加索引路由,以便列出独立于父资源的所有项
我有一个属于Ruby on rails 4 Rails 4-如何为嵌套资源添加索引路由,以便列出独立于父资源的所有项,ruby-on-rails-4,nested-attributes,nested-routes,Ruby On Rails 4,Nested Attributes,Nested Routes,我有一个属于Foo的嵌套资源Bar。我可以成功列出属于任何给定Foo的所有Bar对象。但我也希望能够从它们所属的Foo对象生成一个包含所有Bar项的视图 模型结构为: # app/models/foo.rb class Foo < ActiveRecord has_many :bars end # app/models/bar.rb class Bar < ActiveRecord belongs_to :foo end 我从该配置中获得了预期的路由: foo_ba
Foo
的嵌套资源Bar
。我可以成功列出属于任何给定Foo
的所有Bar
对象。但我也希望能够从它们所属的Foo
对象生成一个包含所有Bar
项的视图
模型结构为:
# app/models/foo.rb
class Foo < ActiveRecord
has_many :bars
end
# app/models/bar.rb
class Bar < ActiveRecord
belongs_to :foo
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
我需要的是为bar#index
生成一个路由,该路由不在foo
的上下文中。换句话说,我基本上想要:
bars GET /bars(.:format) bars#index
我尝试过使用浅层选项,因此:
# config/routes.rb
resources :foos, shallow: true do
resources :bars
end
但是,根据,这不支持:index操作
最好的方法是什么?有一个有用的堆栈溢出讨论,使用
before\u filter
确定范围——但它是从2009年开始的。感谢您提供有关如何正确设置控制器和config/routes.rb
文件的具体指导 如果要保留范围索引方法foo_bars
和单独的bars
路由/视图:
在routes.rb中创建自定义路由:
get 'bars' => 'bars#index', as: :bars
get 'bars' => 'bars#index', as: :bars
在栏中设置索引方法,如链接中所述,或者简单地:
def index
if params[:foo_id]
@bars = Foo.find(params[:foo_id]).bars
else
@bars = Bar.all
end
end
然后创建一个bar
视图目录(如果没有)和index.html.erb
如果不想保留作用域索引方法foo\u bar
:
在routes.rb中创建自定义路由:
get 'bars' => 'bars#index', as: :bars
get 'bars' => 'bars#index', as: :bars
编辑现有管线以排除嵌套索引:
resources :foos do
resources :bars, except: :index
end
然后,条
控制器可以是:
def index
@bars = Bar.all
end
然后创建一个bar
视图目录(如果没有)和index.html.erb
单独添加资源:bar
不起作用?