rails ルーティング (.:format) とは 何
rails routes のコマンドをターミナルで入力すると、Railsで作られているルーティングの一覧が表示されます。
$ rake routes
Prefix Verb URI Pattern Controller#Action
tweets GET /tweets(.:format) tweets#index
POST /tweets(.:format) tweets#create
new_tweet GET /tweets/new(.:format) tweets#new
edit_tweet GET /tweets/:id/edit(.:format) tweets#edit
tweet GET /tweets/:id(.:format) tweets#show
PATCH /tweets/:id(.:format) tweets#update
PUT /tweets/:id(.:format) tweets#update
DELETE /tweets/:id(.:format) tweets#destroy
真ん中のURI pattern( /tweets(.:format) )のとこにある、(.:format) って何?って話です。
結論:URLの先に送るファイルの形式である
基本次のページを表示するって時は.htmlファイルを利用すると思うんですよ。そのファイル形式を(:format)という変数として扱いますよ〜って話だという。例えば次のページが.pdfファイルだったら、format は .pdfということになる。
このくらいの認識でいいのかなと。
このformatを使う時が来るのは、railsのcontrollerにrespond_toというレスポンスの形式ごとに対応を分ける記述をする時とかです。
この構文の意味は、@messageを保存する時に、formatがhtml形式で送られた時とjson形式で送られた時で対応を変えるというものである。
jsonやxmlというのはjavascriptを扱ってレスポンスを飛ばした時に送られてくるデータ形式です。詳しくはajaxなどを説明する別なところで。
このように送られてくるデータ形式で対応を変える時に意識するのが、formatという変数である。
以上。備忘備忘。
参考:
● https://stackoverflow.com/questions/20320263/what-does-format-mean-in-rake-routes
● https://techacademy.jp/magazine/24827