codemonk
codemonk

Reputation: 59

How do I create a restful api on top of a resource that has different methods to return different results?

I have this resource

class Role < ActiveRecord::Base
   # lists all the system-level roles
  def Role.system_roles
    Role.find_all_by_system(true, :order => 'name')
  end

  # lists all the project-level roles
  def Role.project_roles
    Role.find_all_by_system(false, :order => 'name')
  end

  # lists all roles that can be used for workflow enforcement
  def Role.filter_roles
    not_for_filters = ['admin', 'manager']
    Role.project_roles.reject{|role| not_for_filters.include? role.name}
  end
end

Now REST API standards say you must return the resource this way

/roles

that is it.

Well in the index method of the controller I was doing this only

module Api::V1::Setup
  class RolesController < ApplicationController
    include ApiHelper

    layout nil

    def index
      system_roles_data = Role.system_roles
      render :json => roles_data, :status => :ok
    end
  end
end

I see other posts that suggest, well, pass in a parameter. I do not want to do that. Can the following be supported?

/roles/system_roles
/roles/project_roles

What should be in the routes file?

Upvotes: 0

Views: 75

Answers (1)

holographic-principle
holographic-principle

Reputation: 19738

If you create the corresponding methods in your roles_controller.rb (system_roles and project_roles), you could have something like this:

resources :roles do
  collection do
    get 'system_roles'
    get 'project_roles'
  end
end

The system_roles controller method would return Role.system_roles and project_roles would return Role.project_roles, respectively.

Upvotes: 1

Related Questions