【Rails】jbulder의 기초, 사용법

4156 단어 JbuilderRails
그룹 제작은 jbuilder를 사용했기 때문에 학습 내용을 총괄했습니다.

jbuilder란?


jbuilder란 JSON 형식의 데이터를 간단하게 만들 수 있는gem이다.기본값은 Rail로 가져옵니다.

jbuilder로 할 수 있는 일

app/view/〇〇.json.jbuilder 파일 내의 json 대상에 대해 여러 가지 방법을 사용하여 JSON 형식의 문자열의 데이터를 간단하게 만들 수 있다.
나는 API를 두드리는 일을 할 수 있다고 생각한다.(가능)
'두드리기 API'에 관한 이 글은 매우 참고 가치가 있다.

사용법


Rails 및 Vuejs를 사용하여 얻은 데이터는 이미 제작된 구상에 따라 진행됩니다.

1. Jbuilder를 가져왔는지 확인


Gemfile
ruby '2.7.3'
gem 'rails', '~> 6.1.4'
・・・
gem 'jbuilder', '~> 2.7'

2. 컨트롤러 준비

localhost/api/v1/comments.json에서 데이터를 처리할 수 있도록 컨트롤러를 설정하십시오.
app/controller/api/v1/comments_controller.rb
class Api::V1::CommentsController < ApiController
  def index
    @comments = Comment.all
  end
end

3. jbuilder 파일 만들기


각 방법의 후술.
app/views/api/v1/comments/index.json.jbuilder
json.set! :comments do
  json.array! @comments do |comment|
    json.extract! comment, :id, :context
  end
end

4. 생성된 json 데이터 확인


액세스http://localhost/api/v1/comments.json※ 두 가지 수상한 댓글이 있으니 숨겨주세요.

메서드

  • json.extract!: 첫 번째 매개변수에 지정된 인스턴스 변수의 데이터를 JSON 형식의 문자열로 반환합니다.
  • 〇〇json.jbundler
    json.extract! @commnet, :id, :context
    
    # 実行結果=> {"id": 1, "context": "hogehoge"}
    
  • 네스트링
    네스트된 구조로 속성을 분류하려면 다음과 같이 하십시오.
  • 〇〇json.jbundler
    json.set! commnets do
      json.extract! @commnet, :id, :context
    end
    # 実行結果=> {"comments":[{"id": 1, "context": "hogehoge"}]}
    
  • json.set!: 반환 키와 값이 쌍인 JSON 형식의 문자열
  • 〇〇json.jbundler
    json.set! "context", "hogehoge"
    # 実行結果=> {"context": "hogehoge"}
    
  • json.array!: 모델 내의 데이터를 배열에 저장하고 JSON 형식의 문자열로 되돌아오기
  • 〇〇json.jbundler
    json.array! @comments, :id, :context
    # 実行結果=> [{"id": 1, "context": "hogehoge"},{"id": 2, "context": "hojihoji"}]
    

    참고 문장

    좋은 웹페이지 즐겨찾기