【问题标题】:How can I add attributes to rendered JSON from relationship without nesting?如何在不嵌套的情况下从关系中向呈现的 JSON 添加属性?
【发布时间】: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


    【解决方案1】:

    您可以使用as_json 方法非常简单地自定义对象的 json 序列化。

    为此,您可以这样做:

    def as_json(*args)
      hash = super(*args)
      hash.merge!(hash.delete("thumbnails"))
    end
    

    或者你可以超级手动完成

    def as_json(*args)
      hash = super()
      thumbnails.each do |thumb|
        # build thumbnail json
      end
    end
    

    您不必依赖 ActiveRecord 超级简单的 json 序列化方法。

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多