Modelクラスを継承する
公開日:
:
Ruby on Rails
記事内に広告を含む場合があります。記事内で紹介する商品を購入することで、当サイトに売り上げの一部が還元されることがあります。
generate model
% ruby script/generate model super_class
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/super_class.rb
create test/unit/super_class_test.rb
create test/fixtures/super_classes.yml
exists db/migrate
create db/migrate/010_create_super_classes.rb
% ruby script/generate model sub_class
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/sub_class.rb
create test/unit/sub_class_test.rb
create test/fixtures/sub_classes.yml
exists db/migrate
create db/migrate/011_create_sub_classes.rb
model classを編集
% cat app/models/super_class.rb
class SuperClass < ActiveRecord::Base
end
% cat app/models/sub_class.rb
class SubClass < SuperClass
end
migrate fileを編集
% cat db/migrate/010_create_super_classes.rb
class CreateSuperClasses < ActiveRecord::Migration
def self.up
create_table :super_classes do |t|
t.column :name, :string
t.column :type, :string
end
end
def self.down
drop_table :super_classes
end
end
% cat db/migrate/011_create_sub_classes.rb
class CreateSubClasses < ActiveRecord::Migration
def self.up
create_table :sub_classes do |t|
t.column :name, :string
t.column :type, :string
end
end
def self.down
drop_table :sub_classes
end
end
rake db:migrateする
% rake db:migrate
== 10 CreateSuperClasses: migrating ===========================================
-- create_table(:super_classes)
-> 0.0581s
== 10 CreateSuperClasses: migrated (0.0582s) ==================================
== 11 CreateSubClasses: migrating =============================================
-- create_table(:sub_classes)
-> 0.0078s
== 11 CreateSubClasses: migrated (0.0079s) ====================================
consoleを叩いてみる
>> SuperClass.find(:all)
=> []
>> SubClass.find(:all)
=> []
>> SuperClass.create(:name=>'super1')
=> #<SuperClass id: 1, name: "super1", type: nil>
>> SubClass.create(:name=>'sub1')
=> #<SubClass id: 2, name: "sub1", type: "SubClass">
tableをのぞいてみる
SELECT * FROM super_classes;
id | name | type
----+--------+----------
1 | super1 |
2 | sub1 | SubClass
(2 rows)
SELECT * FROM sub_classes;
id | name | type
----+------+------
(0 rows)
generate modelのオプションを調査
sub_classesテーブルは不要なので、classファイルだけgenerateする方法を調べる。
% ruby script/generate model
Usage: script/generate model ModelName [field:type, field:type]
Options:
--skip-timestamps Don't add timestamps to the migration file for this model
--skip-migration Don't generate a migration file for this model
--skip-fixture Don't generation a fixture file for this model
skip-migrationとかを指定すればいいみたい。