LoginSignup
0
1

More than 5 years have passed since last update.

Active Record を学ぶ

Last updated at Posted at 2017-07-27

Active Record を学ぶ

Active Recordにおける規約

命名ルール

  • モデルのクラス名は大文字から始まる単数形、データベースのテーブル名は小文字の単数形
モデル/クラス テーブル/スキーマ
Post posts
MicroPost micro_posts
  • 外部キーはテーブル名の単数形_id

  • 名前が予約された?カラム

名前 役割
id 主キーであり、自動的に作成される。
created_at レコード作成日時を格納する。自動的に作成される。
updated_at レコードの最終更新日時を格納する。自動的に作成される。
lock_version 楽観的ロックを利用するときに使う
type 単一継承テーブルを行うときに使う
関連付け名_type ポリモーフィックアソシエーションを行うときに使う
テーブル名_count 関連付けられている所有オブジェクトの数をキャッシュ
  • テーブル名、主キー名はオーバーライド可能

関連付け

関連付けの種類

  • belongs_to
  • has_one
  • has_many
  • has_many :through 結合モデルを介して多対多関係を表す
  • has_one :through
  • has_and_belongs_to_many

belongするほうが持ち主のidを外部キーとして持つ

ポリモーフィック関連付け

ある一つのモデルを、「そのモデルと関連付け可能なモデル」たちに対して関連付けることができる

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

参考

Active Record の基礎
Active Record の関連付け (アソシエーション)

0
1
0

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
0
1