railsの「設定より規約」の意味
railsはよく「設定より規約」(CoC: convention over configuration)と言われます。
この意味が全然わかっていなかったのですが、今日実感しました。
Layouts and Rendering in Rails — Ruby on Rails Guides
こちらにも書いてあるのですが、下記のようなコードがあったとします。
rails g model book rails g controller books index
app/models/book.rb
class BooksController < ApplicationController end
config/routes
resources : books
ここでrake routes
を実行します。
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
app/views/books/index.html.erb
<h1>Books#index</h1> <p>Find me in app/views/books/index.html.erb</p>
app/controllers/books_controller
class BooksController < ApplicationController end
def index
を削除しております。
ここで/booksにアクセスしてみると、なんとつながります!
controllerを設定しなくてもつながるのは、設定よりも規約でrailsが自動的にapp/views/books/index.html.erb
を探しているからです。
これはわかりやすい例ですね。