2016-04-03 62 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数组 –