【问题标题】:2 Restful routes for one Controller2 个用于一个控制器的 Restful 路由
【发布时间】:2017-07-19 01:57:38
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    我找到了解决办法

      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}
    

    效果很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 2012-12-24
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      相关资源
      最近更新 更多