Skip to content

Instantly share code, notes, and snippets.

@dtuite
Created September 23, 2015 11:01
Show Gist options
  • Save dtuite/161d765b679fb5c908d6 to your computer and use it in GitHub Desktop.
Save dtuite/161d765b679fb5c908d6 to your computer and use it in GitHub Desktop.
Assigning PROs to polymorphic associations
require 'active_record'
ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: ":memory:"
)
ActiveRecord::Schema.define do
create_table :audits do |table|
table.column :user_id, :integer
table.column :user_type, :string
end
end
class Audit < ActiveRecord::Base
belongs_to :user, polymorphic: true
end
class User
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Naming
def initialize
@attributes = AttributeSet.new({ 'id' => 42 })
end
def attributes
@attributes
end
def self.primary_key
'id'
end
def id
attributes['id']
end
def persisted?
false
end
end
audit = Audit.new
audit.user = User.new
audit.save!
# A sample Gemfile
source "https://rubygems.org"
gem "activerecord"
gem "sqlite3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment