Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering rails polymorphic association object to JSON

In the index action in my controller I am returning an array of Picture model that should be rendered to JSON.

def index
  @pictures = Pictures.all
  respond_to do |format|
    format.json { render json: @pictures.to_json( include: [:imageable] ) }
  end
end

This model is configured with polymorphic association.

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable

  attr_accessible :name
end

class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable

  attr_accessible :type
end

The array of pictures will include Picture object with an imageable association to both Employee and Product. How can I render to json the imageable association object differently include both Employeee and Product specific fields?

Thanks you, Asaf

like image 722
asaf am Avatar asked Nov 26 '25 05:11

asaf am


1 Answers

I would recommend you to use something like JBuilder to build your json response.

Then, you create a template file named index.json.jbuilder with your logic to build your json.

You will be able to easily build your json depending on your objects.

For instance:

json.array! @pictures do |picture|
  json.picture_attribute1 = picture.picture_attribute1
  json.picture_attribute2 = picture.picture_attribute2
  if picture.imageable.is_a?(Employee)
    json.employee_name = picture.imageable.name
  else
    json.product_name = picture.imageable.name
  end
end

Please check out the document of JBuilder to find out how to use it.

like image 90
Arkan Avatar answered Nov 27 '25 20:11

Arkan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!