0

I have an object which has a reference to another using the :through approach.

When I perform the "show" method, the objects details are returned but not its associated objects. I've tried including the objects in the find like so:

@recipe = Recipe.includes(:quantities).find(params[:id])

but to no avail.

When I debug the code and do

@recipes.quantities

then I'm returned the correct set but the set isn't returned in the json by default. How I can make it so?

Gerard
  • 4,818
  • 5
  • 51
  • 80
  • To clarify your question: What you are asking is "When I have an object with associations, how do I retrieve the object and all of its relationships in such a way that I can serialize the object and its associations to json?" Is that correct? – Marc Talbot Feb 06 '12 at 14:56
  • More or less yes. The quantities associations are not sent back down in the json with @recipe – Gerard Feb 06 '12 at 14:59
  • I think that's the expected behavior. When you serialize an object to json, it serializes that object, not related objects. You can still serialize an object and it's relationships, but I think you'll need to do this by explicitly serializing the relationship objects. – Marc Talbot Feb 06 '12 at 15:04
  • Yep I can pass down the associated objects individually but it'd be nice to just send down the one single object complete with associated objects. – Gerard Feb 06 '12 at 15:10

1 Answers1

3

In your show method do something like this

def show
  @recipe = Recipe.includes(:quantities).find(params[:id])

   respond_to do |format|
     format.html
     format.json { render json: @recipe.as_json(:include => :quantities)}
   end
 end

This is actually kinda hidden in the Rails source, but as_json makes more sense to use as per an answer on this question.

Documentation: ActiveModel::Serializers::JSON

Community
  • 1
  • 1
Azolo
  • 4,353
  • 1
  • 23
  • 31