(.:format) について

以前から、resouces でルーティング書いた際に生成される、(.:format) が何物なのか、よくわかっていませんでした。

以下のような、rake routes コマンド打つと出てくるやつです。

   Prefix                   Verb          URI Pattern                 Controller#Action

     root      GET            /                                    todos#index

    todos                 GET      /todos(.:format)             todos#index

                               POST       /todos(.:format)              todos#create

new_todo               GET          /todos/new(.:format)      todos#new

edit_todo               GET          /todos/:id/edit(.:format)  todos#edit  

     todo                  GET       /todos/:id(.:format)         todos#show

                               PATCH     /todos/:id(.:format)         todos#update

                               PUT      /todos/:id(.:format)         todos#update

                               DELETE   /todos/:id(.:format)         todos#destroy

 先日勉強しててやっとわかったので、記事にしておこうと思います。

 

 

(.:format) とは

フォーマットを分けるために記載するオプション。

デフォルトではhtmlとなっている。

html 以外には、XMLjson などのフォーマットが選べる。

 

 

(.:format) の具体的な使い方

コントローラーにおいて、以下のように定義。

class TodosController < ApplicationController

    def index
        @todo = Todo.new
        @todos = Todo.order('created_at ASC')
        respond_to do |format|
            format.html
            format.json {render json: @todo}
            format.xml {render xml: @todo}
        end
    end

end

 

URLでlocalhost:3000/todos に普通にアクセスすると、以下のように、views/todos/index.thml のビューファイルが返ってくる。

 

 

localhost:3000/todos.json にアクセスすると、以下のようにjson形式で返ってくる。

 

localhost:3000/todos.xml にアクセスすると、以下のようにxml形式で返ってくる。