2一个控制器的静止路由

时间:2017-02-28 07:47:03

标签: ruby-on-rails routing ruby-on-rails-5

我没有为我的特殊问题找到任何东西。存在一些相关的问题,但没有解决这类问题:

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?type = user

     

对于客户:/ users?type = customer

拥有以下内容会更好:

/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种不同的方法(一种针对客户,一种针对用户)

1 个答案:

答案 0 :(得分: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}

那是完美的