【发布时间】:2011-05-24 20:31:45
【问题描述】:
问题是:我正在使用活动记录并返回一些照片对象。这些照片对象的最终消费者将是一个移动应用程序。
响应需要返回缩略图版本移动开发人员已要求返回的 JSON 看起来像这样..
{
"root_url":'http://place.s3.amazonaws.com/folder/',
"image_300":'image_300.jpg',
"image_600":'image_600.jpg',
"image_vga":'image_VGA.jpg',
"image_full":'image.jpg'
}
不是这样的:
{
"root_url":'http://place.s3.amazonaws.com/folder/',
"thumbnails": {
"image_300":'image_300.jpg',
"image_600":'image_600.jpg',
"image_vga":'image_VGA.jpg',
"image_full":'image.jpg'
}
}
到目前为止,最简单的方法是为每个缩略图创建列,然后哇哦,它的工作原理。我不喜欢被锁定,因为如果我们以后想要不同的缩略图,这意味着将列添加到数据库等。我更喜欢在模型类中指定缩略图或者有一个单独的缩略图表表格中每一行的拇指。
我查看了委托,composition_of,在连接中使用 GROUP_CONCAT..,在 to_json 中使用 :method=> ..这些看起来都不像选项。有没有简单的方法可以做到这一点?
基本模型示例:
class Photo < ActiveRecord::Base
has_many :thumbnails, :as => :thumbs_for #polymorphic
end
class Thumbnail < ActiveRecord::Base
# columns = name, filename
belongs_to :thumb_for, :polymorphic => true
end
到目前为止,结果看起来像这样,基于 jesse reiss 的回答
def as_json(options)
options ||= {} #even if you provide a default, it ends up as nil
hash = super(options.merge({:include => :thumbnails}))
if thumbs = hash.delete(:thumbnails)
thumbs.each {|t| hash.merge!({t['name']=>t['filename']})}
end
hash
end
【问题讨论】:
标签: ruby-on-rails ruby json activerecord