設定
rails の設定は、ほとんどベースクラスのクラスメソッドで行う。
設定する場所は
- config/environment.rb
- クラス定義のとき
config/environment.rb では、config(Rails::Configuration)オブジェクトを使う。
config . action_controller は、ActionController::Base と同じ意味。
オプションの値にはシンボルが多用される。シンボルが使われるのは、
- ハッシュのキー
- モデル名 (例) has_many :line_items
- メソッド名 (例) before_filter :foo_bar
- クラス名
クラスを指定する場合は、シンボルを使う場合とクラスを直接指定する場合の2種類がある。
基本的にはシンボルを使う。シンボルを使うことで、規約に従いクラスのrequireをRailsに
まかせることができる。
シンボルを使わなければならないもの
シンボル、クラスどちらでもかまわないもの
クラスをそのまま指定しなければならないもの
- observe Hoge
- before_filter HogeFilter (シンボルだとメソッド名と解釈される)
マイグレーション
- rails demo
- config/database.yml
development: adapter: mysql database: demo_development username: hoge password: host: localhost encoding: utf8 socket: /var/run/mysqld/mysqld.sock
- config/environment.rb
$KCODE = 'UTF8'
- app/controllers/application.rb
class ApplicationController < ActionController::Base before_filter :set_charset private def set_charset headers["Content-Type"] = "text/html; charset=UTF-8" end end
- db/create_database.sql
drop database if exists demo_development; create database demo_development; grant all on demo_development.* to 'hoge'@'localhost'; exit
- script/generate migration FooBar
- rake migrate (VERSION=x)
外部キー制約やユニーク制約*1は今のところ手動だと思う。
class AddForeignKeyOrders < ActiveRecord::Migration def self.up add_index :orders, :product_id execute "ALTER TABLE orders ADD CONSTRAINT orders_product_id_fk FOREIGN KEY (product_id) REFERENCES products (id)" end def self.down execute "ALTER TABLE orders DROP FOREIGN KEY orders_product_id_fk" remove_index :orders, :product_id end end
- rake db_schema_dump
- rake db_schema_import
schema.rbというファイルにスキーマがダンプされる。
手動でやったもの(execute)は、schema.rbに反映されない。
*1:add_index の :uniqueオプションがあった