Skip to content

Instantly share code, notes, and snippets.

@furaji
Last active August 29, 2015 14:00
Show Gist options
  • Save furaji/dcb746c838515d8c197d to your computer and use it in GitHub Desktop.
Save furaji/dcb746c838515d8c197d to your computer and use it in GitHub Desktop.
RailsでSingle Table Inheritance

単一テーブル継承の実装

参考

モデル

  • Message
  • GoodMessage(Messageを継承)
  • BadMessage(Messageを継承)

データの保存

Message.create(title: 1)
GoodMessage.create(title: 'good', good: 111)
BadMessage.create(title: 'bad', bad: 222)
mysql> select * from messages;
+----+-------+-------------+------+------+
| id | title | type        | good | bad  |
+----+-------+-------------+------+------+
|  1 | 1     | NULL        | NULL | NULL |
|  2 | good  | GoodMessage | 111  | NULL |
|  3 | bad   | BadMessage  | NULL | 222  |
+----+-------+-------------+------+------+

子クラスでデータを保存すると、typeにクラス名が自動で入る。

class BadMessage < Message
end
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.string :title, null: false
t.string :type
t.string :good
t.string :bad
end
end
end
class GoodMessage < Message
end
class Message < ActiveRecord::Base
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment