ruby-on-rails – Rails 4渲染json嵌套对象

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 4渲染json嵌套对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要渲染Json一个复杂的结构.我有下一个结构工作:
render :json => @booking,:include => [:paypal,:boat_people,:boat => {:only => :boat_model,:include => {:boat_model => {:only => :name,:include => { :boat_type => {:only => :name}}}}}]

但是我无法将一些其他嵌套属性的port属性添加到:boat,例如:boat_model(在同一级别).

更新:

虽然它不起作用,但我包含了我的port属性.

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

我的意思是,boat_model和port都是船的属性.

这是模型对象:

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

解决方法

我知道了.
render :json => @booking,:boat => {:only => :name,:include => {:port => {:only => :name,:include => {:city => {:only => :name,:include => {:country => {:only => :name}}}}},:boat_model => {:only => :name,:include => {:boat_type => {:only => :name}}}}}]

猜你在找的Ruby相关文章