Created
September 23, 2015 11:01
-
-
Save dtuite/161d765b679fb5c908d6 to your computer and use it in GitHub Desktop.
Assigning PROs to polymorphic associations
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
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! |
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
# 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