你好我有很多路线,如下面的
resources :users do
resources :shipping_methods, only: [:new, :create, :edit, :update, :destroy]
resources :cart_items, only: [:create, :index, :destroy]
resources :relationships, only: [:create, :destroy]
resources :addresses, only: [:new, :create, :edit, :update, :destroy]
end
他们都产生以下路线
/users/:id/nested_route
例如,编辑送货方法视图会生成以下内容
/users/1/shipping_methods/11/edit
如何让所有这些路线产生这个:
/username/nested_route
例如,上面的编辑送货方法视图应生成以下内容:
/username/shipping_methods/11/edit
答案 0 :(得分:2)
这是实现这一目标的方法之一。覆盖path
资源的users
,并使用collection
作为子资源。它为您提供路径/:user_id/shipping_methods/new
resources :users, path: ':user_id' do
collection do
resources :shipping_methods, only: [:new, :create, :edit, :update, :destroy]
resources :cart_items, only: [:create, :index, :destroy]
resources :relationships, only: [:create, :destroy]
resources :addresses, only: [:new, :create, :edit, :update, :destroy]
end
end
覆盖to_param
模型的User
方法,以便在路由器中使用username
而不是id
def to_param
self.username.parameterize
end
要在子路由器中查找用户User.find_by(username: params[:user_id]