2

내 컨트롤러의 색인 동작에서 JSON으로 렌더링해야하는 그림 모델 배열을 반환합니다.렌더링 레일 다형성 연관 객체를 JSON에

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

이 모델은 다형성 연관으로 구성됩니다.

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 

사진 배열에는 Employee와 Product 모두에 이미지 가능하게 연결된 그림 개체가 포함됩니다. json에 이미지 가능 연결 객체 을 다르게 표현하려면에는 Employeee 및 Product 고유 필드가 모두 포함됩니까? 나는 당신이 당신의 JSON 응답을 구축 JBuilder 같은 것을 사용하는 것이 좋습니다

답변

2

감사를, Asaf.

그런 다음 로직을 사용하여 index.json.jbuilder라는 템플릿 파일을 만들어 json을 빌드하십시오.

개체에 따라 json을 쉽게 만들 수 있습니다. 예를 들어

:

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 

를 사용하는 방법을 알아 제이빌더의 문서를 확인하시기 바랍니다.

+0

큰 접근! 나는 jbuilder로 뛰어 들었다. –