Build correct JSON

64 Views Asked by At

I try to render a correct formatted json:

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

In my model I have to do this:

  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

My problem is that like this it returns:

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

What i dont like about this JSON is that photo in the Json is rendered as String:

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

I would prefer to have it not encoded, for example like this:

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

I would say the problem is my code: The encode:

   Jbuilder.encode do |json| 

So in order fix my problem i tried:

   Jbuilder.new do |json|

But then I get a error in:

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

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

What do I wrong and how can I fix my code? Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

In order to make it work i had to change my code to:

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