Nick M
Nick M

Reputation: 2532

Dynamic Rails routes at runtime

I have an application with two types of users - employees and clients, clients place Orders that employees process.

For each type of user I have a separate controller OrdersController that offers a variety of actions and different types of views.

I'd like to be able to do redirect_to order_path(@order) within shared partials so that the right controller is accessed depending on type of user.

Eg: order_path(Order) should translate to /employees/orders/ID for employees and /clients/orders/ID for clients.

Preferably without hacks like "dispatch controllers" that issue further redirects based on user type, or sub-classing Orders for each type of user.

How do I set up my routing for this?

Upvotes: 0

Views: 39

Answers (1)

user229044
user229044

Reputation: 239311

This isn't really a job for "dynamic routes", the routing table is static by design.

Instead, you can define your own helper methods that look at the current user type, and invoke the correct route helper.

For example:

# app/helpers/application_helper.rb

def order_path(order)
  if current_user.is_a? Employee
    employee_order_path(order)
  else
    user_order_path(order)
  end
end

Upvotes: 1

Related Questions