什么是Polymorphic Associations

A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belongs to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared.

polymorphic association 是一個(gè)比較亮瞎眼的高級(jí)關(guān)聯(lián),用這種關(guān)聯(lián),可以讓一個(gè)model被兩個(gè)或兩個(gè)以上的model擁有,一個(gè)簡(jiǎn)單的單一關(guān)聯(lián),例如,你有一張pic model,同時(shí)屬于employee和product,可以這樣聲明:

class Picture < ApplicationRecord
    belongs_to :imageable, polymorphic: true
end

class Product < ApplicationRecord
    has_many :pictures, as: :imageable
end

class Employee < ApplicationRecord
    has_many :pictures, as: :imageable
end

你可以把一個(gè)polymorphic的屬于關(guān)系聲明當(dāng)作一個(gè)其他mode可以使用的接口。
比如你實(shí)例化了一個(gè)Employee model,你可以取回一個(gè)圖像的collection:@employee.pictures

同樣地,你也可以取回@product.pictures

如果你有一個(gè)實(shí)例化了一個(gè)圖片的model,你可以通過(guò)@picture.imageable,為了讓這些工作有效,你需要聲明一個(gè)外鍵,和一個(gè)字段類(lèi)型。

class CreatePictures < ActiveRecord::Migration[5.0]
  def change
    create_table :pictures do |t|
      t.string  :name
      t.integer :imageable_id
      t.string  :imageable_type
      t.timestamps
    end
 
    add_index :pictures, [:imageable_type, :imageable_id]
  end
end

你也可以使用t.references的形式

class CreatePictures < ActiveRecord::Migration[5.0]
  def change
    create_table :pictures do |t|
      t.string :name
      t.references :imageable, polymorphic: true, index: true
      t.timestamps
    end
  end
end

下面這樣圖片可以讓你清晰的看清楚這三張model之間的關(guān)系以及polymorphic的用法

image.png

來(lái)源:Rails Guides
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,240評(píng)論 0 23
  • 主人公:一對(duì)夫妻(有兒子),夫妻中男主人公的同事一女孩 故事發(fā)生一年前,男的暗送秋波那個(gè)女孩,朋友圈發(fā)布很多僅限那...
    路人甲乙組團(tuán)閱讀 349評(píng)論 0 1
  • 孩子的大腦是一片空白, 任人涂畫(huà) 于是, 我便相信了罪孽。 孩子的心靈是一派單純, 隨人引導(dǎo) 所以, 你便相信了邪...
    眸弋閱讀 177評(píng)論 0 2
  • 三年,一千零九十五天,兩萬(wàn)六千二百八十個(gè)小時(shí),九千四百六十萬(wàn)零八千秒。 你走了好久好久,好久。在那里會(huì)不會(huì)想我,...
    埋木未枯飄零華閱讀 476評(píng)論 1 0
  • 今天上樓時(shí)抬頭一掃看見(jiàn)有一層的房門(mén)旁不知道放了什么,黑漆漆一團(tuán)。等上去了定睛一看才發(fā)覺(jué)是個(gè)老人,頭發(fā)斑白中帶著些焦...
    希聲孟極閱讀 302評(píng)論 0 0

友情鏈接更多精彩內(nèi)容