views:

26

answers:

1

I'm writing an API; in this API, I have a FruitBasket model which has Fruits. A particular Fruit may belong to more than one FruitBasket at a time. FruitBasket and Fruit are both ActiveRecord objects.

If someone performs a GET on /fruit/100/baskets, I want to provide a JSON list of baskets which have that fruit, in the form of basket IDs. If there's only one basket, I want to redirect to /basket/x, where x is the id of the basket. Something like this:

class FruitsController < ApplicationController
  respond_to :json

  def baskets
    @baskets = Fruit.find(params[:id]).baskets
    if baskets.size == 1
      # What goes here?
    else
      respond_with @baskets
    end
  end
end

What do I put in my routes and the FruitsController to pull this off?

+1  A: 

I'm not sure you really want to redirect them over there, but if you must:

...
if @baskets.size == 1
  redirect_to @baskets.first      
else
...

However, would expect an API to simple return an array of Baskets, and if there was only one basket, then it would be an array with one item.

Jesse Wolgamott