2017-02-28 54 views
0

我没有找到任何关于我的特殊问题。目前存在这种问题的一些相关的问题,但没有:2个控制器的宁静路线

Rails 4 match all routes for one controller

One controller for multiple routes

我有以下的用户模型:

class User < ApplicationRecord 
    has_many :customers, foreign_key: :user_id, class_name: 'User' 
    has_many :users 
end 

用户可以拥有的客户,也有用户。并且每个用户都可以拥有的客户(如果需要的用户也该媒体链接可以有顾客等一个)

现在我想建立一个控制器为每种类型的用户。

class UsersController < ApplicationController 
    def index 
    @users = User.type_for(params[:type], current_user) 
    end 
end 

的routes.rb中也明确:

resources :users 

但我不希望以下途径:

对于用户:/用户类型=用户

为客户提供:/用户类型=客户

这将是更好的有以下几点:

/users => UserController#index (params[:type] = user 
/customers => UserController#index (params[:type] = customer 

resources :users, class_name: 'User', type: :user 
resources :customers, class_name: 'User', type: :customer 

我刚刚发现一个类似

resources :users, :collection => { :customers => :get } 

,但为了这个,我创建了2种不同的方法(一个客户,一个用户)

回答

0

我找到了解决办法

resources :users, type: :user 
    resources :customers, controller: :users, type: :customer 

这会产生以下途径

users GET /users(.:format)    users#index {:type=>:user} 
      POST /users(.:format)    users#create {:type=>:user} 
new_user GET /users/new(.:format)   users#new {:type=>:user} 
edit_user GET /users/:id/edit(.:format)  users#edit {:type=>:user} 
    user GET /users/:id(.:format)   users#show {:type=>:user} 
      PATCH /users/:id(.:format)   users#update {:type=>:user} 
      PUT /users/:id(.:format)   users#update {:type=>:user} 
      DELETE /users/:id(.:format)   users#destroy{:type=>:user} 
customers GET /customers(.:format)   users#index {:type=>:customer} 
      POST /customers(.:format)   users#create {:type=>:customer} 
new_customer GET /customers/new(.:format)  users#new {:type=>:customer} 
edit_customer GET /customers/:id/edit(.:format) users#edit {:type=>:customer} 
customer GET /customers/:id(.:format)  users#show {:type=>:customer} 
      PATCH /customers/:id(.:format)  users#update {:type=>:customer} 
      PUT /customers/:id(.:format)  users#update {:type=>:customer} 
      DELETE /customers/:id(.:format)  users#destroy {:type=>:customer} 

这就是工作完美