Last active
June 19, 2018 04:03
-
-
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
This file contains 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
# 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 |
This file contains 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
# 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 |
This file contains 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
# 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