LoginSignup
5
8

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-12-11

準備

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}

参考

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8