Skip to content

Instantly share code, notes, and snippets.

@dented
Created April 8, 2017 09:39
Show Gist options
  • Save dented/6faec379fd2d1a240045b61d78eebd15 to your computer and use it in GitHub Desktop.
Save dented/6faec379fd2d1a240045b61d78eebd15 to your computer and use it in GitHub Desktop.
Support Polymorphic for STI
class Manager < User
def can_do_stuff
end
end
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
# 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
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