【问题标题】:Build correct JSON构建正确的 JSON
【发布时间】:2015-02-12 09:48:25
【问题描述】:

我尝试渲染一个正确格式的 json:

   render json: {photo: @photo.as_json(with_thumbs_url: true)}

在我的模型中,我必须这样做:

  def as_json(options={})
    if options[:with_thumbs_url].present?
      Jbuilder.encode do |json| 
        json.(self, :id, :beschreibung, :date, :art) 
        json.thumbs self.photo_thumbs.map{|e| e.file.url(:medium)}
      end
    end
  end

我的问题是这样返回:

 {photo: "{"id":288,"beschreibung":"Anfang","date" ...system/photos/6267/medium/136.webp?1413823129"]}"}

我不喜欢这个 JSON 的地方在于,Json 中的 photo 被渲染为字符串:

        "{"id":288,"beschreibung":"

我宁愿不对其进行编码,例如:

  {photo: {id: "288", beschreibung: "Anfang" ...

我会说问题出在我的代码上:encode:

   Jbuilder.encode do |json| 

所以为了解决我的问题,我尝试了:

   Jbuilder.new do |json|

然后我得到一个错误:

   render json: {photo: @photo.as_json(with_thumbs_url: true)}

   wrong number of arguments (0 for 1..2)

我做错了什么以及如何修复我的代码?谢谢

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 jbuilder


【解决方案1】:

为了使它工作,我不得不将我的代码更改为:

def as_json
  Jbuilder.new do |json|
    # your stuff
  end.attributes!
end

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 2011-04-23
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多