Rails / JBuilder - Entity array with has_many attributes
- by seufagner
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" ]
}
]}