我有一個模型軌-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