78
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails g model ~ テーブル作成虎の巻 ~

Last updated at Posted at 2015-09-05

パターン

  1. 普通のテーブル
  2. 外部キー制約
  3. validation
  4. index
  5. unique

普通のテーブル

単数形
カラム:データ型 カラム:データ型
カンマはいらない

rails g model Author name:string age:integer

外部キー制約

これでauthor_idがカラムに追加される。

rails g model Book title:string author:references

validation

modelに後から追加する。

Book.rb

class Book < ActiveRecord::Base
  validates :title, presence: true
  validates :hoge, length: { minimum: 2 } 
end

index

特定のカラムをB木構造にして検索をかけるので、速い。ただ頻繁に使うカラムでないと逆に負債。

作成時↓

rails g model Book title:string:index

しかし、

rails g migration AddIndexToBook 

等と打って、migrationファイルいじるほうが一般的かも知れない。

unique

uniqueでありたい時もありますね

rails g model Book title:string:unique
78
63
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
78
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?