2011-04-12 8 views
2

serialize_with_options을 사용하는 동안 배열과 관련하여 예상대로 작동하지 않는다는 것을 알게되었습니다.to_json에 사용자 정의 속성 추가

@ posts.to_json을 호출하는 @posts (README에서 볼 수 있듯이) 배열은 사용자를 포함하지 않거나 제목 만 표시하지 않습니다.

예상되는 동작인지 확실하지 않습니다. 관련 항목을 찾을 수 없기 때문에 뭔가 빠졌습니다.

레일 사용 3.0.4

PS. 모델의 JSON 형식에 2 개의 사용자 정의 속성을 포함 시키려면 어떤 대안이 있습니까?

+0

당신이 더 명확하게 당신이 달성 원하는 작업을 조금 자세히 설명해 할 수 있습니까? '@ post.to_json (: only => : title) '제목 만 표시하려면 트릭을해야합니다. json에 사용자를 포함 시키려면'@ post.to_json (: include => : user)' – rubish

답변

2

고려 그런 ActiveModel::Serializers::JSON.as_json 과부하 :

class Post 
    def as_json(options) 
    # make sure options is not nil 
    options ||= {} 
    # call super with modified options 
    super options.deep_merge(methods: [:custom_attr1, :custom_attr2]) 
    end 

    def custom_attr1 
    "return first custom data" 
    end 

    def custom_attr2 
    "return second custom data" 
    end 
end 

#rspec this like that 
describe Post do 
    subject { Post.new } 
    it "has custom data" do 
    to_json.should include(
     { custom_attr1: "return first custom data", 
     custom_attr2: "return second custom data"}) 
    end 
end