これが私のセットアップであり、その後に私が達成しようとしていることの説明が続きます。
class Layer < ActiveRecord::Base
has_and_belongs_to_many :components
end
class Component < ActiveRecord::Base
has_and_belongs_to_many :layers
end
class ImageComponent < Component
# I want this table to inherit from the Component table
# I should be able to add image-specific fields to this table
end
class VideoComponent < Component
# I want this table to inherit from the Component table
# I should be able to add video-specific fields to this table
end
私ができるようにしたいこと:
layer.components << ImageComponent.create
layer.components << VideoComponent.create
ImageComponent
実際には、とVideoComponent
を実際に継承する必要があることを認識していActiveRecord::Base
ます。Rails でモデルのサブクラス化を適切に実装する方法はありますか?
今、私は自分のComponent
モデルをpolymorphic
そのようなものImageComponent
に設定していVideoComponent
ますhas_one :component, as: :componentable
。ただし、これにより、コードに煩わしさと醜さのレイヤーが追加されます。
image_component = ImageComponent.create
component = Component.create
component.componentable = image_component
layer.components << component
これを説明する簡単な方法は、レイヤーとコンポーネントの間に habtm 関係を実装したいということだと思います。複数のタイプのコンポーネント (ImageComponent、VideoComponent など) があり、それぞれの基本構造は同じですが、関連付けられているフィールドは異なります。これを達成する方法について何か提案はありますか? 私のコードはハックっぽいので、何かが欠けているように感じます。