Rails Routing: one controller. One model with type. Multiple routes

I have one model named Factors which is of two types: ['personal', 'advisor']

I want to have one controller FactorsController

that has all the same actions for both types Factors

, but only ever uses one type. The type it uses is based on the route used to get it. For example,

/personal

will be routed to factors#index

and fill @factors

Factor.personal

/advisors

will be routed to factors#index

and filled @factors

withFactor.advisors

How do I customize the setting?

+3


source to share


3 answers


You can add routes

type_regexp = Regexp.new([:personal, :advisor].join("|"))
resources :factors, path: ':type', constraints: { type: type_regexp }

      



and you will be able to use the user params[:type]

in your controllers, which will give you flexibility if you want to change routes in the future.

It also gives you the ability to use factors_path(type: :personal)

in views.

+3


source


You can add this to your routes:

resources :factors, :path => :personal
resources :factors, :path => :advisor

      



After that, he will have both personal and advisors. Then you will want the indices # of the indices to determine which path was used (you can use it request.url

) and populate @factors

accordingly.

+2


source


I would create three controllers:

class PersonalController < FactorController
  def factor
    Factor.personal
  end
end

class AdvisorController < FactorController
  def factor
    Factor.advisors
  end
end

class FactorController < ApplicationController
  #all the shared stuff here, using the factor method from each in your methods
end

      

and then the routes will be as follows:

route '/personal' => PersonalController#index
route '/advisors' => AdvisorController#index

      

0


source







All Articles