我有个模特
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“(它不使用序列化程序)。
请帮帮忙。
发布于 2016-04-04 03:09:32
序列化程序具有new方法。你也可以从控制员那里打电话来。
render json: BlogSerializer.new(Blog.all)对于数组,请使用ArraySerializer。示例:
blogs = ActiveModel::ArraySerializer.new(blogs, each_serializer: ArticleSerializer)https://stackoverflow.com/questions/36382679
复制相似问题