Rails / JBuilder - Entity array with has_many attributes

Posted by seufagner on Stack Overflow See other posts from Stack Overflow or by seufagner
Published on 2013-10-20T15:52:00Z Indexed on 2013/10/20 15:53 UTC
Read the original article Hit count: 269

Filed under:
|
|

I have two models, Person and Image and I want return an json array of Persons with your Images.

But I dont want return all Image attributes, but produces a different result.

Code below:

class Person < ActiveRecord::Base
  has_many :images, as: :imageable

  validates :name, presence: true

  accepts_nested_attributes_for :images, :reject_if => lambda { |img| img['asset'].blank? }

end

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true

  mount_uploader :asset, ImageUploader

  validates :asset, presence: true
end

zzz.jbuilder.json template

json.persons(@rodas, :id, :name, :images)

json produced:

{
"rodas": [{
  "id": 4,
  "name": "John",
  "images": [
    {
      "asset": { "url": "/uploads/image/xxxx.png" }
    },
    {
      "asset": { "url": "/uploads/image/yyyyy.jpeg" }
    }
  ]},
  {
  "id": 19,
  "name": "Mary",
  "images": [
    {
      "asset": { "url": "/uploads/image/kkkkkkk.png" }
    }
  ]
}]
}

I want something like:

{
"rodas": [
{
  "id": 4,
  "name": "John",
  "images": [ "/uploads/image/xxxx.png" , "/uploads/image/yyyy.jpeg" ]
},
{
  "id": 10,
  "name": "Mary",
  "images": [ "/uploads/image/dddd.png" , "/uploads/image/xxxx.jpeg" ]
}

]}

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JSON