1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails で HTML と JSON フォーマットを両方返す方法

Posted at

はじめに

タイトルの通りですが、久しぶりに Rails アプリケーションを実装したので備忘録です。

あと、こうやって共有すると、記憶にグッと入りますよね。笑

ちょっと最近の雑感ですが、動くコードをそのまま貼りたいというのがあって、Qiita で投稿されている記事なんかも頻繁に参考にさせて頂いていますが、動作しないという事態によく遭遇します。

ですので、動作環境と実装に必要なコードをファイルパス付で(ここ結構大事だと思っている)書いていく習慣を付けていこうと思っています。

動作確認環境

  • OS
    • Ubuntu 18.04 LTS
  • 仮想環境
    • Docker 19.03.8
  • Rails
    • Rails 6.0.3.1

やりたかったこと

  • Rails で一通りの CRUD アプリケーションを実装後に、フロントエンドの JavaScript SDK を作成し、連携させたい
  • そのために、エンドポイントによって、レスポンスボディを HTML と JSON で分けたかった

コード

app/controllers/articles_controller.rb
class ArticlesController < ApplicationController

  def index
    @articles = Article.all
    respond_to do |format|
      format.html 
      format.json { render json: @articles }
    end
  end
end

実行結果

  • HTML
    2020-05-31_13h40_50.png

  • JSON
    2020-05-31_13h40_31.png

終わりに

今回は、非常に簡単な事例ですが、なんらかお役に立てれたら幸いです。

さて、いよいよフロントアプリケーション(ember.js とか ActiveResource.js)とインテグレーションをしてみようかと思います。

参考(感謝)

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?