ruby-on-rails - 别名可能与不同模型的相同别名有许多关联?

我有一个 Article 模型,它可以有许多不同类型的内容块。所以一个 Article 可以有很多 HeadingBlocksParagraphBlocks 像这样:

class Article < ApplicationRecord
  has_many :heading_blocks
  has_many :paragraph_blocks
end

class HeadingBlock < ApplicationRecord
  belongs_to :article
end

class ParagraphBlock < ApplicationRecord
  belongs_to :article
end

我希望能够使用相同的名称 (blocks) 为 HeadingBlockParagraphBlock 起别名,因此如果我有一篇文章的实例,我可以执行以下操作:

@article.blocks // returns all heading blocks and paragraph blocks associated

这在 Rails 中可行吗?如果是这样,您能否提供一个示例,说明如何使用相同名称为多个关联中的多个模型起别名?

谢谢你。

回答1

您可以有一个返回块数组的方法:

class Article < ApplicationRecord
  has_many :heading_blocks
  has_many :paragraph_blocks

  # NOTE: returns an array of heading and paragraph blocks
  def blocks
    heading_blocks + paragraph_blocks
  end
end

您可以重新组织关系以具有多态关联:

class Article < ApplicationRecord
  has_many :blocks
end

# NOTE: to add polymorphic relationship add this in your migration:
#       t.references :blockable, polymorphic: true
class Block < ApplicationRecord
  belongs_to :article
  belongs_to :blockable, polymorphic: true
end

class HeadingBlock < ApplicationRecord
  has_one :block, as: :blockable
end

class ParagraphBlock < ApplicationRecord
  has_one :block, as: :blockable
end

如果可以将 HeadingBlock 和 ParagraphBlock 合并到一个数据库 table 中:

class Article < ApplicationRecord
  has_many :blocks
end

#  id
#  article_id
#  type
class Block < ApplicationRecord
  belongs_to :article
  # set type as needed to `:headding` or `:paragraph`
end

# NOTE: I'd avoid STI; but this does set `type` column automatically to `ParagraphBlock`
# class ParagraphBlock < Block
# end