我有一個Article模型,可以有許多不同型別的內容塊。所以一個Article可以有很多HeadingBlocks這樣的ParagraphBlocks:
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
我希望能夠同時使用相同的名稱 ( ) 進行別名HeadingBlock,ParagraphBlock因此blocks如果我有一篇文章的實體,我可以執行以下操作:
@article.blocks // returns all heading blocks and paragraph blocks associated
這在 Rails 中可行嗎?如果是這樣,您能否提供一個示例,說明如何使用相同名稱為多個關聯中的多個模型起別名?
謝謝你。
uj5u.com熱心網友回復:
您可以有一個回傳塊陣列的方法:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478520.html
標籤:轨道上的红宝石
