ruby-on-rails-4 – Rails 4 – 如何为嵌套资源添加索引路由,以
发布时间:2020-12-17 04:17:23 所属栏目:百科 来源:网络整理
导读:我有一个属于Foo的嵌套资源栏.我可以成功列出属于任何给定Foo的所有Bar对象.但是我也希望能够生成一个视图,其中所有Bar项目都列在一起,来自它们所属的任何Foo对象. 模型结构是: # app/models/foo.rbclass Foo ActiveRecord has_many :barsend# app/models/b
我有一个属于Foo的嵌套资源栏.我可以成功列出属于任何给定Foo的所有Bar对象.但是我也希望能够生成一个视图,其中所有Bar项目都列在一起,来自它们所属的任何Foo对象.
模型结构是: # 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 我需要的是生成一个bar #index的路由,它不在foo的上下文中.换句话说,我基本上想要: bars GET /bars(.:format) bars#index 我尝试过使用浅选项,因此: # config/routes.rb resources :foos,shallow: true do resources :bars end 但是,根据documentation,这不支持:index action. 最好的方法是什么?有一个有用的Stack Overflow讨论here,使用before_filter来确定范围 – 但它是从2009年开始.了解如何正确设置控制器和config / routes.rb文件的任何具体指导! 解决方法
如果要保持范围索引方法foo_bars和单独的条形路径/视图:
在routes.rb中创建自定义路由: 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 然后创建一个条形视图目录(如果没有)和index.html.erb. 如果您不想保留范围索引方法foo_bars: 在routes.rb中创建自定义路由: get 'bars' => 'bars#index',as: :bars 编辑现有路由以排除嵌套索引: resources :foos do resources :bars,except: :index end 然后吧控制器可能只是: def index @bars = Bar.all end 然后创建一个条形视图目录(如果没有)和index.html.erb. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |