Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

rails標準機能jbuilderを使用してJsonレスポンスを返す

More than 3 years have passed since last update.

準備

routesでレスポンスのフォーマットにjsonを設定する

config/routes.rb
get 'user/index'   => 'user#index', defaults: { format: :json }

レスポンスの定義を実装

値をパースしないでまとめて渡す場合

app/view/users/index.json.jbuilder
json.array!(Use.all) do |user|
  json.call(user, :id, :name)
end
#=> {id: XX, name: XX}

値をパース(編集)する時など個別に設定する場合

app/view/users/index.json.jbuilder
json.array!(Use.all) do |user|
  #json.key value 形式で渡す
  json.id user.id
  json.name user.name.strip!
end
#=> {id: XX, name: XX}

参考

http://llcc.hatenablog.com/entry/2015/03/07/103121

SoarTec-lab
freelance software developer/rails contributor https://contributors.rubyonrails.org/contributors/soartec-lab/commits
classi
学校の先生・生徒・保護者向けのB2B2Cの学習支援Webサービス「Classi(クラッシー)」 を開発・運営している会社です。
https://classi.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away