别名可能与不同型号的相同别名有很多关联吗?

Possible to alias has many associations with the same alias with different models?

我有一个 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 中可行吗?如果是这样,您能否提供一个示例,说明如何使用相同的名称为具有多个关联的多个模型设置别名?

谢谢。

你可以有一个方法 returns 块数组:

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