LoginSignup
106
90

More than 5 years have passed since last update.

respond_toを初心者向けに完全分解

Last updated at Posted at 2019-02-18

この記事の対象

respond_toがよくわからなくてとりあえずググった人

構成

・respond_toのできる事
・使い方

respond_toのできる事

def destroy
    @tweet = Tweet.find(params[:id])
    respond_to do |format|
      if @tweet.destroy
         format.html { redirect_to root_path }
         #root_pathへリダイレクトする
         format.js { render :action => "index" }
         #.index.html.erbで作成されたものをjson形式で表示する。
      end
    end  
end

destroy action が呼び出された時、formatがhtmlで指定されていたらroot_pathにリダイレクト、jsonで指定されていたらindex.html.erbをindex.html.jsで返す

どうやって使うか

respond_to do |format|
    format.html 
    format.js { @user }
end  

こんな感じで、処理の終わりを指定されたformatにより変更できるように書きます。

書き方は

format.形式 { 行いたい処理の内容 }

です。

上記の例だと、何も処理を書かなければデフォルトのテンプレートが指定されたフォーマットで表示されます。

format.jsを使用した例だと、@userの情報をjson形式で返します(もちろんアクション内で@userの情報を取得しておく必要があります。)

最後に

難しかったので、間違ってるとこあれば指摘ください。

106
90
1

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
106
90