我过去曾经读过,嵌套多种资源并不是一种好的做法。
我有模特,酒店,房间和参观。 (H has_many R,R有很多V)
如果你不应该多次筑巢,如下面......
resources :hotels do
resources :rooms do
resources :visits
end
end
那么最佳做法是什么?
我希望能够通过房间/ 3 /访问等方式检索特定房间的所有访问...但我目前无法做到这一点,因为上述代码会破坏最佳实践嵌套。
答案 0 :(得分:2)
浅嵌套
“避免深度嵌套的一种方法(如上所述)是生成在父级下作用域的集合操作,以便了解层次结构,但不嵌套成员操作。”
See Rails Guide on Routing Section 2.7.2 Shallow Nesting for more information
在你的情况下,你会看到:
resources :hotels do
resources :rooms, shallow: true
end
resources :rooms, only: [] do
resources :visits
end
这相当于:
resources :hotels do
resources :rooms, only: [:index, :new, :create]
end
resources :rooms, only: [:show, :edit, :update, :destroy]
并将为您提供以下路线:
GET /hotels/:hotel_id/rooms(.:format) rooms#index
POST /hotels/:hotel_id/rooms(.:format) rooms#create
new_hotel_room GET /hotels/:hotel_id/rooms/new(.:format) rooms#new
edit_room GET /rooms/:id/edit(.:format) rooms#edit
room GET /rooms/:id(.:format) rooms#show
PATCH /rooms/:id(.:format) rooms#update
PUT /rooms/:id(.:format) rooms#update
DELETE /rooms/:id(.:format) rooms#destroy
hotels GET /hotels(.:format) hotels#index
POST /hotels(.:format) hotels#create
new_hotel GET /hotels/new(.:format) hotels#new
edit_hotel GET /hotels/:id/edit(.:format) hotels#edit
hotel GET /hotels/:id(.:format) hotels#show
PATCH /hotels/:id(.:format) hotels#update
PUT /hotels/:id(.:format) hotels#update
DELETE /hotels/:id(.:format) hotels#destroy
room_visits GET /rooms/:room_id/visits(.:format) visits#index
POST /rooms/:room_id/visits(.:format) visits#create
new_room_visit GET /rooms/:room_id/visits/new(.:format) visits#new
edit_room_visit GET /rooms/:room_id/visits/:id/edit(.:format) visits#edit
room_visit GET /rooms/:room_id/visits/:id(.:format) visits#show
PATCH /rooms/:room_id/visits/:id(.:format) visits#update
PUT /rooms/:room_id/visits/:id(.:format) visits#update
DELETE /rooms/:room_id/visits/:id(.:format) visits#destroy