【Rails】なんたらかんたら_pathって実際はなにしてるんだっけ?的な話
$ruby -v ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0] $rails -v Rails 4.1.5
ここで土台作りする。
$rails new study_path $cd study_path $rails g scaffold book isbn:string title:string price:integer publish:string published:date cd:boolean $rake db:migrate
さあ始めよう!!
app/views/books/index.html.erbを見る(hamlにしちゃいましたhttp://html2haml.heroku.com/)
%h1 Listing books %table %thead %tr %th Isbn %th Title %th Price %th Publish %th Published %th Cd %th{:colspan => "3"} %tbody - @books.each do |book| %tr %td= book.isbn %td= book.title %td= book.price %td= book.publish %td= book.published %td= book.cd %td= link_to 'Show', book %td= link_to 'Edit', edit_book_path(book) %td= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %br/ = link_to 'New Book', new_book_path
さらに以下の行に注目
%td= link_to 'Edit', edit_book_path(book) = link_to 'New Book', new_book_path
この「go_to_the_path」な書き方。
「便利なグローバルメソッドか変数みたいなやつで、どこからでも呼べる!」といいう考えをなんとなく持っていた。が、全然違うらしい。以下のコマンドを打ってみる。
$rake routes Prefix Verb URI Pattern Controller#Action books GET /books(.:format) books#index POST /books(.:format) books#create new_book GET /books/new(.:format) books#new edit_book GET /books/:id/edit(.:format) books#edit book GET /books/:id(.:format) books#show PATCH /books/:id(.:format) books#update PUT /books/:id(.:format) books#update DELETE /books/:id(.:format) books#destroy
(すごく見にくいけど)真ん中の列のパスを左の列_pathで呼び出す。すると右の列のコントローラーのアクションが自動的に呼ばれる。という仕組み。
で、このテーブルはどう作られるかというと、config/routes.rbに書いてあるように記載されるらしい。