Rails 4 render json nested objects

Viewed 11498

I need to render as Json a complex structure. I have next structure working:

render :json => @booking, :include => [:paypal, 
                                       :boat_people,
                                       :boat => {:only => :boat_model, :include => {:boat_model => {:only => :name, :include => { :boat_type => {:only => :name}}}}}] 

but I´m not able to add a port attribute with some other nested attributes to :boat, such as :boat_model (at same level).

UPDATE:

Although it´s not working, I include my port attribute.

render :json => @booking, :include => [:paypal, 
                                       :boat_people,
                                       :boat => {:only => [:boat_model => {:include => {:boat_model => {:only => :name, :include => { :boat_type => {:only => :name}}}}},
                                                           :port => {:include => :city => {:only => name}}]}]

I mean, boat_model and port are both boat attributes.

This is the model object:

class Boat < ActiveRecord::Base

  attr_accessor :price
  @price

  attr_accessor :extrasPrice
  @extrasPrice

  def as_json(options = { })
    h = super(options)
    h[:price] = @price    
    h[:extrasPrice] = @extrasPrice
    h
  end


  belongs_to :boat_model
  belongs_to :port
  belongs_to :state
  has_many :photos
end
2 Answers
Related