除了单表继承之外,您还可以考虑使用has_one
关联。
您的所有子类型都有一个 post-info,它是一般的帖子名称、slug 等(并且 post-info 在多态上属于子类型)。
这样,您将拥有一个发布信息表,以及每个子类型的表。
但是,在模型中你必须做更多的处理:
class PostInfo < ActiveRecord::Base
belongs_to :post, :polymorphic => true
# will need these 2 fields: :post_id, :post_type (might be AudioPost, ImagePost, etc)
end
class AudioPost < ActiveRecord::Base
has_one :post_info, :as => :post
# you may also want these:
accept_nested_attributes_for :post_info
delegate :name, :slug, :posted_at, :to => :post_info
end
所以现在如果你想获得所有的帖子,你可以:
Blog.find(1).post_infos
post_info.post # => audio_post, image_post, or whatever depending on post_type
如果您不想使用.post_infos
,您也可以更改所有这些名称,例如:
class Post < ActiveRecord::Base
belongs_to :actual_post # actual_post_id, actual_post_type
end
class AudioPost < ActiveRecord::Base
has_one :post, :as => :actual_post
accept_nested_attributes_for :post
delegate :name, :slug, :posted_at, :to => :post
end
现在,你有:
posts = Blog.find(1).posts
actual_post = posts.first.actual_post # => an audio_post instance
actual_post.name # => same as actual_post.post.name, so you do not need the name field in the AudioPost model