渲染json和嵌套属性

时间:2013-03-26 23:54:29

标签: ruby-on-rails ruby json

我有这些课程:

class Product
 attr_accessible :name, ...
 has_many :images
end

class Image
 attr_accessible :image, :position, :product_id, :title
 belongs_to :product
end

动作:

def list
  render :json => {:Result => "OK", :Records => Product.all}
end

如何将每个产品的自己的图像作为嵌套属性包含在内,而不是枚举产品中的所有属性?

1 个答案:

答案 0 :(得分:0)

您可以使用to_json(:include => :attr)

def list
  render :json => {:Result => "OK", :Records => Product.all}.to_json(:include => :images)
end