多くの属性を共有するBookおよびDownloadモデルがあるため、私の目標はDownloadableResourceモデルから共通の属性を継承することです。STI
を見ましたが、代わりに抽象基本モデルクラスの方法を使用しました。
モデル:
class DownloadableResource < ActiveRecord::Base self.abstract_class = true attr_accessible :title, :url, :description, :active, :position validates :title, :url, :description, presence: true scope :active, where(active: true).order(:position) end class Book < DownloadableResource attr_accessible :cover_url, :authors validates :cover_url, :authors, presence: true end class Download < DownloadableResource attr_accessible :icon_url validates :icon_url, presence: true end
移行:
class CreateDownloadableResources < ActiveRecord::Migration def change create_table :downloadable_resources do |t| t.string :title t.string :url t.text :description t.boolean :active, default: false t.integer :position t.timestamps end end end class CreateBooks < ActiveRecord::Migration def change create_table :books do |t| t.string :cover_url t.string :authors t.timestamps end end end class CreateDownloads < ActiveRecord::Migration def change create_table :downloads do |t| t.string :icon_url t.timestamps end end end
移行後、新しいブックを作成すると、結果は期待とはかけ離れています:
> Book.new
=> #<Book id: nil, cover_url: nil, authors: nil, created_at: nil, updated_at: nil>
ActiveRecordモデルが継承を介して共通のコードを共有しながら、異なるデータベーステーブルに永続化できるように、Abstract Base Model Classテクニックを実装する方法に光を当てることができますか?