0

i didn't find anything for my special question. There exist some related question but nothing for this kind of problem:

Rails 4 match all routes for one controller

One controller for multiple routes

I have the following user model:

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

A user can have customers and also have users. And each of the users can have customers (and if needed also users which allready can have customers and so one)

Now i want to build one controller for each type of users.

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

The routes.rb is also clear:

resources :users

But i don't want the following routes:

For Users: /users?type=user

For Customers: /users?type=customer

It will be nicer to have the following:

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

Like a

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

I just found one similar

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

but for this i have to create 2 different methods (one for customers, one for users)

Community
  • 1
  • 1
rob
  • 2,136
  • 8
  • 29
  • 37

1 Answers1

0

i found the solution

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

this generates the following routes

    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}

thats worked perfect

rob
  • 2,136
  • 8
  • 29
  • 37