我需要帮助实现或将其分解为单表继承 (STI)。我已经阅读过它,但我还不确定我是否以正确的方式进行。如果你们有实施它的建议。或者即使它与我现在所拥有的非常不同,请建议。
所以,通常我有以下课程(所有型号)。
class Article < ActiveRecord::Base
has_many :attachments
has_many :medias
has_one :banner
accepts_nested_attributes :medias
...
end
class Attachment < ActiveRecord::Base
belongs_to :article
end
class Media < Attachment
default_scope { where(attachment_type: 'media') }
def audio?; media_type == 'audio'; end
def video?; media_type == 'video'; end
validate :embed_url, presence: true if :video?
def path
if audio?
# Different audio path
elsif video?
# Different video path
end
end
after_commit :process_audio_file
def process_audio_file; ...; end
after_commit :process_video_file
def process_video_file; ...; end
end
class Banner < Attachment
default_scope { where(attachment_type: 'banner') }
...
end
通常它也会正常工作..
article = Article.first
first_media = article.medias.first
banner = article.banner
但后来我注意到这Media
可能会很臃肿,并且有太多不同的逻辑需要为不同的 media_types 做不同的事情。所以我试图通过这样做将它们分开:
class Article < ActiveRecord::Base
has_many :attachments
has_many :medias
has_one :banner
accepts_nested_attributes_for :medias
end
class Attachment < ActiveRecord::Base
belongs_to :article
end
class Media < Attachment
default_scope { where(attachment_type: 'media') }
end
class AudioMedia < Media
default_scope { where(media_type: 'audio') }
def path
# Audio path
end
after_commit :process_audio_file
def process_audio_file; ...; end
end
class VideoMedia < Media
default_scope { where(media_type: 'video') }
validate :embed_url, presence: true
def path
# Video path
end
after_commit :process_video_file
def process_video_file; ...; end
end
现在在这里我将逻辑彼此分开。伟大的!但现在它带来了一些问题,例如:
article = Article.first
first_media = article.medias.first
在这样做时,我只是在Media
上课......要说AudioMedia
上课,我要做的是:
"#{first_media.media_type}Media".constantize.find(first_media.id)
另外,为了让我的nested_attributes 工作,我必须定义
accepts_nested_attributes_for :audio_medias
accepts_nested_attributes_for :video_medias
让它正常工作?然后我必须定义他们的关系,比如:
has_many :medias
has_many :audio_medias
has_many :video_medias
有什么建议吗?谢谢和欢呼!
编辑
添加了相关的表格和字段
articles
id
[some_other_fields]
attachments
id
article_id
attachment_type # media, banner, etc...
media_type # audio, video, etc...
[some_other_fields]