Advanced rest interface tips

All the tutorials I see on doing a rest interface with rails only show
how to do it with resources 1 level deep, i.e., they don’t show a good
way to go about doing a rest interface for nested type rest
interfaces. For example:

service.com/api/user/1/company/2

If I was doing this with rails would I have to use 2 different
controllers: users_controller & companies_controller?

Are there any good guides for this?

Thanks

Probably, and you can use nested routes like this:

map.resources :users do |users|
users.resources :companies
end

aurélien

Yes, I would use two controllers. The users_controller would look like
a normal RESTful controller.
The companies_controller requires a little more work.
I tend to do most of it with before_filters

class CompaniesController < ApplicationController

before_filter :find_user
before_filter :find_companies, :only => :index
before_filter :find_company, :only => [:show,:update,:edit,:destroy]

protected

def find_user
@user = User.find_by_id(params[:user_id])
end

def find_companies
@companies = @user.companies
end

def find_company
@company = @user.companies.find_by_id(params[:id])
end

public

def index

For the new/create actions, you should use:
@company = @user.companies.build(params[:company])

Which makes the new company belong to the @user and (I think) updates
any counter cache you might be using.
Your company_path now takes two arguements, @user and @company; the
companies_path takes @user.

Those methods are the bare minimum, and in a real application, I would
probably have something to redirect to a 404 if a user or company
wasn’t found.

In your routes, you will need a declaration as aurélien said.

Depending on the nature of the application, you might want to
substitute the @user in the build statement for something representing
the currently logged in user. Something similar could be done in a
filter method so that the searches for the update, edit, destroy
actions only find companies belonging to the current user.

Hope this helps,
Jonathan

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs