2016-04-03 63 views
1

我有一個模型軌-API:渲染JSON多個值

class Banner < ActiveRecord::Base 
    validates :title, presence: true, length: { maximum: 50 } 
    validates :description, length: { maximum: 200 } 

    belongs_to :document 

    def img_url 
    document.medium_url 
    end 
end 

和串行

class BannerSerializer < ActiveModel::Serializer 
    attributes :id, :title, :description, :img_url, :document_id 
end 

當我使用render json: Banner.all,它響應正確(有 「img_url」 的響應

{ 
"banners": [ 
    { 
     "id": 1, 
     "title": "This is title of banner", 
     "description": "This is long description...", 
     "img_url": "http://localhost:3000//system/documents/attachments/000/000/023/medium/one-piece.jpg?1459601536", 
     "document_id": 23 
    } 
    ] 
} 

但是當我想通過使用其他對象返回。 例如:

render json: { 
     banners: Banner.all, 
     blogs: Blog.all, 
     partners: Partner.all 
    } 

響應不存在「img_url」(它不使用串行器)。

請幫忙。

+0

如果您使用'Blog.all.to_json',該怎麼辦? – ArashM

+0

它不包含img_url,除此之外,橫幅的值變爲字符串 –

+0

好的。那麼使用'as_json'呢? – ArashM

回答

2

串行器有new方法。你也可以從控制器中調用它。

render json: BlogSerializer.new(Blog.all) 

對於數組,使用ArraySerializer。 例如:

blogs = ActiveModel::ArraySerializer.new(blogs, each_serializer: ArticleSerializer) 
+0

我再次測試,它對單個值(例如:BlogSerializer.new(Blog.all.frist) ,但列表不起作用:(。順便說一句:謝謝 –

+0

可能,你有問題的地方。在我的項目中,它的工作。 – 7urkm3n

+0

我找到了一個解決方案,通過使用ArraySerializer :)'ActiveModel :: ArraySerializer.new(博客,each_serializer :ArticleSerializer)'usi ng數組 –