2015年5月13日 星期三

【Ruby on Rails】has_many model using jbuilder

Two model as below

image

group.rb

   1: class Group < ActiveRecord::Base
   2:   has_many :posts
   3:   validates :title,:presence => true
   4: end


post.rb



   1: class Post < ActiveRecord::Base
   2:   belongs_to :group
   3: end

In view/group/index.json.jbuilder



   1: json.groups (@groups) do |group|
   2:   json.extract! group, :id, :title, :description
   3:   json.posts (group.posts) do |post|
   4:    json.extract! post, :id,:comtent
   5:   end
   6: end

So 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: }

沒有留言:

張貼留言