Rails 4渲染json嵌套对象

时间:2013-12-16 19:46:18

标签: ruby-on-rails ruby 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, :include => [:paypal, 
                                       :boat_people,
                                       :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

2 个答案:

答案 0 :(得分:21)

我明白了。

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

答案 1 :(得分:3)

您可能想要一个更强大的系统来显示JSON。内置的Rails助手实际上主要是为简单的添加而设计的,这些添加使用户能够完成他们想要完成的大部分工作。但是,在您的情况下,您正在尝试使其完成比设计更多的操作。

我强烈建议您创建view object或使用像RABL这样的宝石。

我的偏好是将Rabl用于复杂的JSON。它基本上通过构建特定于域的语言为您创建“视图对象”,这使得在rails中构建复杂的JSON对象变得相对容易。

RABL基本上允许您构建格式化JSON而不是HTML的视图。 DSL非常丰富,可以让你做任何你想要的事情。在您的情况下,我认为代码看起来像这样:

app/views/bookings/show.rabl

object @booking
#these are attributes that exist on your booking model: 
attributes :booking_attribute, :other_booking_attribute

child :paypal do
  #these are attributes that exist on your paypal model:
  attributes :paypay_attribute1, :other_paypal_attribute
end

child :boat_people do
  #boat_people attributes that you want to include
  attributes :blah_blah
end

child :boat do
  #boat attributes that you want to include
  attributes :boat_attribute1, :boat_attribute2

  child :boat_model do
    attributes :name

    child :boat_type do
      attributes :name
    end
  end

end