Rails+grape How the API prints information about the table associated with jbuilders in json format

Asked 1 years ago, Updated 1 years ago, 64 views

I'm worried about how to make json templates in jbuilder.

How can I write a template for json in order to provide information about the Post associated with the user in json?

Ideally
From GET to /api/v1/users/all

id
user_name
user_account
user_img
user.post.id
user.post.post_image

I would like to print in json.

Thank you for your cooperation.

User
id —integer
provider:string
user_name —string
user_account:
user_img:
has_many —posts    

Post
id —integer
user_id —Integer
post_image —string
text:string
belongs_to —user
module Cospic
 class API <Grape::API
format —json 
formatter:json,Grape::Formatter::Jbuilder
   # Add prefix to API access
   # ex) http://localhost:3000/api
   prefix "api"

   # Add version information to API access
   # ex) http://localhost:3000/api/v1
   version 'v1',:using=>:path

   resource "users" do
    # GET http://localhost:3000/api/v1/users/all
     desc "User List"
      get: all, jbuilder: 'users' do
       @users=User.all
      end
json.articles@users do|user|
  json.(user,id,:user_name,:user_account,:user_img,:user.post.id,:user.post.post_image)
end

ruby-on-rails json grape

2022-09-29 22:48

1 Answers

There are many ways to write it down, but it's easy to understand.

#xxx.json.jbuilder
json.user_name @user.user_name
[email protected]_account
json.user_img @user.user_img

[email protected] s.each do | post |
   json.post_id post.id
   json.post_image post.post_image
end

For a simple way to use jbuilder, the xxx part of json.xxx is the key to JSON, and the argument is the value of JSON.
If you want a hierarchical structure, you can write it like [email protected] s.each.

#JSON Output
{ 
  "user_name" = > "user_name"
  "user_account" = > "user_account",
  "user_img" = > "user_img",
  "posts" = > [
    { "post_id" = > 1}, { "post_image" = > "post_image"},
    { "post_id"=>1}, {"post_image"=>"post_image"}
  ]
}


2022-09-29 22:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.