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
适当的文件!
如果要保留范围索引方法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
.
归档时间: |
|
查看次数: |
2694 次 |
最近记录: |