我有一个模型轨-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”(它不使用串行器)。
请帮忙。
如果您使用'Blog.all.to_json',该怎么办? – ArashM
它不包含img_url,除此之外,横幅的值变为字符串 –
好的。那么使用'as_json'呢? – ArashM