处理嵌套资源的开箱即用的解决方案是在子资源控制器中处理它:
Sampleapp::Application.routes.draw do
resources :bids
resources :users do
resources :bids # creates routes to BidsController
end
resources :auctions do
resources :bids # creates routes to BidsController
end
end
class BidsController < ApplicationController
before_action :set_bids, only: [:index]
before_action :set_bid, only: [:show, :update, :destroy]
def index
end
# ... new, create, edit, update, destroy
def set_bid
# when finding a singular resources we don't have to give a damn if it is nested
@bid = Bids.find(params[:id])
end
def set_bids
@bids = Bids.includes(:user, :auction)
if params.has_key?(:user_id)
@bids.where(user_id: params[:user_id])
elsif params.has_key?(:auction_id)
@bids.where(auction_id: params[:auction_id])
end
@bids.all
end
end
这里的优点是您可以通过很少的代码重复获得完整的 CRUD 功能。
但是,如果您想拥有不同的视图模板或进行不同的排序等,您可以非常简单地覆盖索引路由。
Sampleapp::Application.routes.draw do
resources :bids
resources :users do
member do
get :bids, to: 'users#bids', :bids_per
end
resources :bids, except: [:index]
end
resources :auctions do
member do
get :bids, to: 'auction#bids', as: :bids_per
end
resources :bids, except: [:index]
end
end
另一种解决方案是创建一个AuctionsBidsController 并这样定义路由:
resources :auctions do
resources :bids, only: [:index], controller: 'AuctionsBids'
resources :bids, except: [:index]
end