Komei22 / rails-tutorial

rails-tutorialのsample_app作っていきます
0 stars 0 forks source link

API関連メモ #114

Open Komei22 opened 7 years ago

Komei22 commented 7 years ago

コントローラ側でレスポンスをjsonとhtmlで分けたいとき

def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
    respond_to do |format|
      format.html { redirect_to root_url and return unless @user.activated? }
      format.json
    end
  end
Komei22 commented 7 years ago

jbuilderを使ったjsonビューの定義

以下のように書くと

show.json.jbuilder

json.extract! @user, :id, :name, :microposts

レスポンス

curl localhost:3000/api/users/1 | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 12616    0 12616    0     0  14237      0 --:--:-- --:--:-- --:--:-- 14239
{
  "id": 1,
  "name": "Example User",
  "microposts": [
    {
      "id": 295,
      "content": "Maxime facilis necessitatibus fuga dolores ullam doloribus.",
      "user_id": 1,
      "created_at": "2017-10-03T08:53:45.000Z",
      "updated_at": "2017-10-03T08:53:45.000Z",
      "picture": {
        "url": null
      }
    },
    {
      "id": 289,
      "content": "Quasi dolorum quibusdam ad aut.",
      "user_id": 1,
      "created_at": "2017-10-03T08:53:45.000Z",
      "updated_at": "2017-10-03T08:53:45.000Z",
      "picture": {
        "url": null
      }
    },
.....

以下のようなレスポンスを期待する場合

curl localhost:3000/api/users/1 | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
.
.
.

"follower": [
    {
      "id": 4,
      "name": "Raheem Gleason"
    },
    {
      "id": 5,
      "name": "Keanu Jast"
    },
    {
      "id": 6,
      "name": "Dr. Deborah Kuphal"
    },
    {
      "id": 7,
      "name": "Mrs. Mario Strosin"
    },
    {
      "id": 8,
      "name": "Mr. Vilma Treutel"
    },
    {
      "id": 9,
      "name": "Jermey Gleichner"
    },
.....

show.json.jbuilder

json.follower do
  json.array! @user.followers do |follower|
    json.id follower.id
    json.name follower.name
  end
end