2017/11/29

Ruby - 使用多態關聯

markdown ## 使用 [多態關聯 Polymorphic Associations](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations) 目的:在一個表格可能被多個表格參考時,不使用多個 references 去儲存參考,而是使用一個 reference + 一個 type 欄位去儲存。 建立: ``` 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 ``` ``` class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true end class Employee < ApplicationRecord has_many :pictures, as: :imageable end class Product < ApplicationRecord has_many :pictures, as: :imageable end ``` 使用: ``` Product.last.pictures Employee.last.pictures ```

沒有留言: