| | 3 | # Returns a JSON string representing the model. Some configuration is |
|---|
| | 4 | # available through +options+. |
|---|
| | 5 | # |
|---|
| | 6 | # Without any +options+, the returned JSON string will include all |
|---|
| | 7 | # the model's attributes. For example: |
|---|
| | 8 | # |
|---|
| | 9 | # konata = User.find(1) |
|---|
| | 10 | # konata.to_json |
|---|
| | 11 | # |
|---|
| | 12 | # {"id": 1, "name": "Konata Izumi", "age": 16, |
|---|
| | 13 | # "created_at": "2006/08/01", "awesome": true} |
|---|
| | 14 | # |
|---|
| | 15 | # The :only and :except options can be used to limit the attributes |
|---|
| | 16 | # included, and work similar to the #attributes method. For example: |
|---|
| | 17 | # |
|---|
| | 18 | # konata.to_json(:only => [ :id, :name ]) |
|---|
| | 19 | # |
|---|
| | 20 | # {"id": 1, "name": "Konata Izumi"} |
|---|
| | 21 | # |
|---|
| | 22 | # konata.to_json(:except => [ :id, :created_at, :age ]) |
|---|
| | 23 | # |
|---|
| | 24 | # {"name": "Konata Izumi", "awesome": true} |
|---|
| | 25 | # |
|---|
| | 26 | # To include any methods on the model, use :methods. |
|---|
| | 27 | # |
|---|
| | 28 | # konata.to_json(:methods => :permalink) |
|---|
| | 29 | # |
|---|
| | 30 | # {"id": 1, "name": "Konata Izumi", "age": 16, |
|---|
| | 31 | # "created_at": "2006/08/01", "awesome": true, |
|---|
| | 32 | # "permalink": "1-konata-izumi"} |
|---|
| | 33 | # |
|---|
| | 34 | # To include associations, use :include. |
|---|
| | 35 | # |
|---|
| | 36 | # konata.to_json(:include => :posts) |
|---|
| | 37 | # |
|---|
| | 38 | # {"id": 1, "name": "Konata Izumi", "age": 16, |
|---|
| | 39 | # "created_at": "2006/08/01", "awesome": true, |
|---|
| | 40 | # "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"}, |
|---|
| | 41 | # {"id": 2, author_id: 1, "title": "So I was thinking"}]} |
|---|
| | 42 | # |
|---|
| | 43 | # 2nd level and higher order associations work as well: |
|---|
| | 44 | # |
|---|
| | 45 | # konata.to_json(:include => { :posts => { |
|---|
| | 46 | # :include => { :comments => { |
|---|
| | 47 | # :only => :body } }, |
|---|
| | 48 | # :only => :title } }) |
|---|
| | 49 | # |
|---|
| | 50 | # {"id": 1, "name": "Konata Izumi", "age": 16, |
|---|
| | 51 | # "created_at": "2006/08/01", "awesome": true, |
|---|
| | 52 | # "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}], |
|---|
| | 53 | # "title": "Welcome to the weblog"}, |
|---|
| | 54 | # {"comments": [{"body": "Don't think too hard"}], |
|---|
| | 55 | # "title": "So I was thinking"}]} |
|---|