Skip to content

Instantly share code, notes, and snippets.

@mrinterweb
Last active June 13, 2018 03:44
Show Gist options
  • Save mrinterweb/99d26f03476cfb807337f734e56bc3c2 to your computer and use it in GitHub Desktop.
Save mrinterweb/99d26f03476cfb807337f734e56bc3c2 to your computer and use it in GitHub Desktop.
# This is a ActiveRecord STI class
class Hyundai < Car
has_one :hyundai_details
delegate *HyundaiDetails::ACCESSIBLE_ACCESSOR_METHODS, to: :hyundai_details
default_scope { includes(:hyundai_details) }
def initialize(args = {})
hyundai_details_attrs = {}
args.each do |key, _val|
if HyundaiDetails::ACCESSIBLE_ATTRS.include?(key)
hyundai_details_attrs[key] = args.delete(key)
end
end
super(args).tap do
build_hyundai_details(hyundai_details_attrs) if new_record?
end
end
end
class HyundaiDetails < ApplicationRecord
ACCESSIBLE_ATTRS = %i[graphics color raditude doors wheels].freeze
ACCESSIBLE_ACCESSOR_METHODS = ACCESSIBLE_ATTRS.map { |attr| [attr, :"#{attr}="] }.flatten.freeze
belongs_to :hyundai
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment