Created
April 8, 2017 09:39
-
-
Save dented/6faec379fd2d1a240045b61d78eebd15 to your computer and use it in GitHub Desktop.
Support Polymorphic for STI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Manager < User | |
def can_do_stuff | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Profile < ApplicationRecord | |
belongs_to :profileable, polymorphic: true | |
# # if don't want to use blanket polymorphic | |
# def profilable_type=(class_name) | |
# super(class_name.constantize.base_class.to_s) | |
# end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# models/concerns/single_table_polymorphic.rb | |
module SingleTablePolymorphic | |
extend ActiveSupport::Concern | |
included do | |
self.reflect_on_all_associations.select{|a| a.options[:polymorphic]}.map(&:name).each do |name| | |
define_method "#{name.to_s}_type=" do |class_name| | |
super(class_name.constantize.base_class.name) | |
end | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ApplicationRecord | |
has_one :profile, as: :profileable, dependent: :destroy | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment