开发者

Build json from ValueObjects in Rails 3?

开发者 https://www.devze.com 2023-03-10 08:30 出处:网络
i was wondering how i can build a json response from a value object? Situation? I want to return clear json, only the field i need in the front-end. Which means: All associations should be included i

i was wondering how i can build a json response from a value object?

Situation?

I want to return clear json, only the field i need in the front-end. Which means: All associations should be included in the json. But开发者_如何学Python again: only the fields I need. This i why i would like to use a special value object (defining the field) on top of my models.

Problem?

Is this a good idea? How to build value objects (VOs) with rails?

Thanks for helping


Of course it's possible. Look here:

Here is an example:

konata.to_json(:only => [ :id, :name ])
# => {"id": 1, "name": "Konata Izumi"}

As you're talking about associations:

konata.to_json(:include => :posts)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
  "created_at": "2006/08/01", "awesome": true,
  "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
            {"id": 2, author_id: 1, "title": "So I was thinking"}]}


This one sounds interesting: http://fabrik42.github.com/acts_as_api/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号