gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:29:32 26 4
gpt4 key购买 nike

我有一个 Article 模型,它可以包含许多不同类型的内容 block 。所以一个 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 中可行吗?如果是这样,您能否提供一个示例,说明如何使用相同的名称为具有多个关联的多个模型设置别名?

谢谢。

最佳答案

你可以有一个返回 block 数组的方法:

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 合并到一个数据库表中:

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

关于ruby-on-rails - 别名可能与不同型号的相同别名有很多关联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72297792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com