views:

24

answers:

1

Is there a consensus best approach to implementing user roles when using RESTful resource routes?

Say I have the following resources:

User has_many Tickets
Event has_many Tickets
Ticket belongs_to Person, Event

And then further say I have two types of Users: customers and agents. Both will log into the system, but with different resource access and functionality based on their roles. For example:

Customers can access:

  • Event index, show
  • Ticket index (scoped by user), show, buy/create, return/delete
  • Person create, show, update

Agents can access:

  • Event index, show, create, update, delete
  • Ticket index, show, sell/create, update, refund/delete
  • Person index, show, create, update, delete

Which of the 4 general approaches below will be cleaner and more flexible?

Separate controllers within role folders and resources in namespaces, eg:

namespace "agent" do
  resources :events, :tickets, :people
end
namespace "customer" do
  resources :events, :tickets, :people
end

Separate controllers by role, eg:

AgentController
  def sell_ticket, etc

CustomerController
  def buy_ticket, etc

Shared controllers with separate actions where needed, eg:

TicketController
  before_filter :customer_access, :only => :buy
  before_filter :agent_access, :except => :buy

  def buy  #accessed by customer to create ticket

  def sell   #accessed by agent to create ticket

Shared actions with conditional statements, eg:

TicketController
  def create
    if @role == :customer
      #buy ticket
    elsif @role == :customer
      #sell ticket
    end
  end
A: 

If you use the same model for customer and agent tickets, there should be no major difference between how they are handled in controller. So, create action will be always like this:

@ticket = Ticket.new(params[:ticket])

if @ticket.save
  redirect_to @ticket
else
  render :action => "new"
end

But your views can be simply customized:

<% if customer? %>
  Customer area.
<% else %>
  Agent area.
<% end %>
Semyon Perepelitsa