简体   繁体   中英

rails polymorphic association on 1 model

Does rails provide multiple polymorphic association. And allow has_many relation.

class Picture < ActiveRecord::Base
  belongs_to :image, polymorphic: true
  belongs_to :icon, polymorphic: true 
end

class Event < ActiveRecord::Base
  has_many :pictures, as: :image
  has_many :pictures, as: :icon
end

Thank you

Rails' active record does allow you to define a polymorphic association.

From the docs :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM