Skip to content
voxdolo edited this page May 18, 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
    person.save # the attributes are already set, so no need to `update_attributes`
    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 and pluralization is 'equipment'), then the plugin will enter an infinite loop. Make sure you differentiate between the plural and singular form of your model by adding an inflection in your initializers.