Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active June 19, 2018 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inopinatus/16e59462f82bee3b8552464e1f59129c to your computer and use it in GitHub Desktop.
Save inopinatus/16e59462f82bee3b8552464e1f59129c to your computer and use it in GitHub Desktop.
Remapping type column values using the Rails 5 Attributes API, good for both STI and polymorphic belongs_to
# lib/attachable_sti_type.rb
class AttachableStiType < ActiveRecord::Type::String
def cast_value(value)
if value =~ /\A([a-z]+)\/([a-z]+)\Z/
"#{$2}/#{$1}_record".classify
else
super
end
end
def serialize(value)
if value && value.underscore =~ /\A([a-z]+)\/([a-z]+)_record\Z/
"#{$2}/#{$1}"
else
super
end
end
def changed_in_place?(original_value_for_database, value)
original_value_for_database != serialize(value)
end
end
# app/models/attachment.rb
class Attachment < ApplicationRecord
belongs_to :document, polymorphic: true
belongs_to :attachable, polymorphic: true, dependent: :destroy, autosave: true
attribute :attachable_type, :attachable_sti_type
#...
end
# config/initializers/types.rb
require 'attachable_sti_type'
ActiveRecord::Type.register(:attachable_sti_type, AttachableStiType)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment