Mike Mike - 1 year ago 63
Ruby Question

When rendering an object in JSON from the controller, how do I include a field from the object's parent?

I’m using Rails 4.2.7. When returning an object via a show method, I want to include an object from the object’s parent. I tried

def show
respond_to do |format|
@my_object = MyObject.find(params[:id])
format.json { render :json => @my_object.to_json(:include => [:parent, :include => :address]) }

However this is producing the error

NoMethodError (undefined method `include' for #<MyObject:0x007fa1b433d788>):

What’s the right way to include an object from my parent?

Edit: here's the parent model in my Rails app

class Parent < ActiveRecord::Base
belongs_to :address, :autosave => true #, dependent: :destroy

Answer Source

Try this one

def show

  @my_object = MyObject.find(params[:id])
  render :json => @my_object.to_json(:include => [:parent => {:include => :address}]) 


You have added include within the include statement,

@my_object.to_json(:include => [:parent, **:include** => :address])

so rails is searching include as one of the method or model.

You can use a array like this for including more than one relationship.

:include => [:parent, :address]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download