Two model as below
group.rb
1: class Group < ActiveRecord::Base
2: has_many :posts3: validates :title,:presence => true
4: endpost.rb
1: class Post < ActiveRecord::Base
2: belongs_to :group 3: endIn view/group/index.json.jbuilder
1: json.groups (@groups) do |group|
2: json.extract! group, :id, :title, :description3: json.posts (group.posts) do |post|
4: json.extract! post, :id,:comtent 5: end 6: endSo input url on browser,we will get
1: {2: "groups":[
3: {4: "id":1,
5: "title":"First",
6: "description":"Testtest",
7: "posts":[
8: {9: "id":1,
10: "comtent":"good"
11: }, 12: {13: "id":2,
14: "comtent":"test2"
15: }, 16: {17: "id":3,
18: "comtent":"test4"
19: } 20: ] 21: } 22: ] 23: }
沒有留言:
張貼留言