views:

49

answers:

1

Disclaimer, I know very little about Rails. I'll try to be succinct.

ModelA belongs_to ModelB ModelB has_many ModelA

The JSON Show action of the ModelA controller should show all ObjectA's that are belonging to the ObjectB of which the ObjectA in question is a member of.

So if I have an ObjectB that contains ObjectA's of ID 1, 2, and 3

When I access

/modela/1.json

I should see

{"modelb":{"id":"1", "modela":[insert a bunch of modela JSON for ID's 1, 2 and 3]}}

I hope this is enough info to go off of... Thanks!

+3  A: 

By default you'll only get the JSON that represents modelb in your example above. But, you can tell Rails to include the other related objects as well:

def export
  @export_data = ModelA.find(params[:id])
  respond_to do |format|
    format.html
    format.json { render :json => @export_data.to_json(:include => :modelb) }
  end
end

You can even tell it to exclude certain fields if you don't want to see them in the export:

render :json => @export_data.to_json(:include => { :modelb => { :except => [:created_at, updated_at]}})

Or, include only certain fields:

render :json => @export_data.to_json(:include => { :modelb => { :only => :name }})

And you can nest those as deeply as you need (let's say that ModelB also has_many ModelC):

render :json => @export_data.to_json(:include => { :modelb => { :include => :modelc }})
Rob Cameron