Railsデータベース学習ノート


Railsフレームワークの強さ、シンプルさ、優雅さはよく知られているので、雑談は多くありませんが、最近学んだRailsのデータベースでの基本的な操作方法をまとめてみましょう.
1.Railsプロジェクトで複数のデータベースの接続を実現する
railsプロジェクトでは、開発、テスト、正式な3つの環境に対応するdevelopment、test、productionの3つの環境が設定されます.
プロジェクトのデータベース構成では、databaseのような3つの環境でのデータベース接続も通常設定されます.yml:
development:
  adapter: mysql2
  encoding: utf8
  host: localhost
  reconnect: false
  database: devlopment
  username: root
  password: mysql

test:
  adapter:......

production:
  adapter:.......

開発中にanotherなどの他のデータベースを使用する必要がある場合はdbのデータは、次のようにします.

another_db:

  adapter: mysql2
  encoding: utf8
  host: localhost
  reconnect: false
  database: another
  username: root
  password: mysql

プロジェクトにuserというモデルがこのデータベースに する があると すると、このような を きます.

#RAILSROOT/app/models/user.rb

class User < ActiveRecord::Base 
end

の のコードを する があります.
establish_connection :another_db

たちのuser modelの などの はanother_に します.db
2.Rails model コマンド
モデル:
Rails g model ModelName  Field1:field_type   Field2:field_type    Field3:field_type    Field4:field_type......

のモデルに しいfieldを します.
rails generate migration AddColumeToTable colume:type

モデルに のfieldを するには、 の に います.
rails generate migration RemoveColumeFromTable colume:type

モデル のfieldの を します.モデル のカラムpointをpointsに を する は、まず の を います.
rails g RenamePointToPoints

20****_を rename_point_to_points.rbのファイルは、upメソッドとdownメソッドでそれぞれ のように されます.
class RenamePointToPoints < ActiveRecord::Migration
  def up
  	rename_column :model_name, :point, :points
  end

  def down
  	rename_column :model_name, :points, :point
  end
end