Skip to content
btelles edited this page Oct 13, 2011 · 10 revisions

Here's a simple example of what a Rails controller with a nested resource might look like before and after a conversion to use decent_exposure:

Before

class PeopleController < ApplicationController
  respond_to :html, :xml, :json
  before_filter :get_company

  def index
    @people = @company.people.where(params.except(:action, :controller, :format))
  end

  def show
    @person = @company.people.find(params[:id])
  end

  def new
    @person = @company.people.build
  end

  def edit
    @person = @company.people.find(params[:id])
  end

  def create
    @person = @company.people.build(params[:person])
    @person.save
    respond_with(@person)
  end

  def update
    @person = @company.people.find(params[:id])
    @person.update_attributes(params[:person])
    respond_with(@person)
  end

  def destroy
    @person = @company.people.find(params[:id])
    @person.destroy
    respond_with(@person)
  end

  private
  def get_company
    @company = Company.find(params[:company_id])
  end
end

After

class PeopleController < ApplicationController
  respond_to :html, :xml, :json

  expose(:company) { Company.find(params[:company_id]) }
  expose(:people) do
    company.people.where(params.except(:action, :controller, :format))
  end
  expose(:person)

  def create
    person.save
    respond_with(person)
  end

  def update
    # the attributes are already set, so no need to `update_attributes`
    person.save
    respond_with(person)
  end

  def destroy
    person.destroy
    respond_with(person)
  end
end

Note on pluralization: If your application does not distinguish between the plural and singular version of a model (e.g. equipment's pluralization is 'equipment'), then the plugin will attempt to constantize the method name and possibly throw an error.

There are two options for resolution:

  • differentiate between the plural and singular form of your model by adding an inflection in your initializers.
  • name the exposure for the collection differently (e.g. company_equipment) and manually specify your scoping by providing a block to the singular resource. Do note that you lose the default behavior if you go this route. Given the effect of adding inflections on URI's, you may be okay with this tradeoff.