【Rails】jbulder의 기초, 사용법
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.extract! @commnet, :id, :context
# 実行結果=> {"id": 1, "context": "hogehoge"}
네스트된 구조로 속성을 분류하려면 다음과 같이 하십시오.
json.set! commnets do
json.extract! @commnet, :id, :context
end
# 実行結果=> {"comments":[{"id": 1, "context": "hogehoge"}]}
json.set!
: 반환 키와 값이 쌍인 JSON 형식의 문자열json.set! "context", "hogehoge"
# 実行結果=> {"context": "hogehoge"}
json.array!
: 모델 내의 데이터를 배열에 저장하고 JSON 형식의 문자열로 되돌아오기json.array! @comments, :id, :context
# 実行結果=> [{"id": 1, "context": "hogehoge"},{"id": 2, "context": "hojihoji"}]
참고 문장
Reference
이 문제에 관하여(【Rails】jbulder의 기초, 사용법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ATSU_PROGRAM_/items/42b83f21657c81a58bd7텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)