Skip to content

Instantly share code, notes, and snippets.

@aalvarado
Last active August 29, 2015 14:16
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 aalvarado/4ce836699d0ffb8b3782 to your computer and use it in GitHub Desktop.
Save aalvarado/4ce836699d0ffb8b3782 to your computer and use it in GitHub Desktop.
# http://stackoverflow.com/questions/28711074/undefined-method-error-for-scope-on-sti-subclass
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails'
gem 'arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :transactions, force: true do |t|
t.string :type
t.references :account
end
create_table :accounts, force: true do |t|
end
end
class Transaction < ActiveRecord::Base
belongs_to :account
scope :deposits, -> { where type: Deposit }
end
class Deposit < Transaction
scope :pending, -> { where state: :pending }
end
class Account < ActiveRecord::Base
has_many :transactions
end
class StiTest < Minitest::Test
def test_sti_scope
a = Account.create
a.transactions.create
Deposit.create account: a
assert_equal Deposit::ActiveRecord_AssociationRelation, a.transactions.deposits.class
end
end
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails'
gem 'arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
require 'pry'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :transactions, force: true do |t|
t.string :type
t.string :state
t.references :account
end
create_table :accounts, force: true do |t|
end
end
class Transaction < ActiveRecord::Base
belongs_to :account
def self.deposits
conditions = where(nil).where_values.reduce(&:and)
Deposit.unscoped.where(conditions)
end
end
class Deposit < Transaction
scope :pending, -> { where state: :pending }
end
class Account < ActiveRecord::Base
has_many :transactions
end
class StiTest < Minitest::Test
def test_sti_scope
a = Account.create
a.transactions.create
Deposit.create account: a, state: :pending
assert_equal a.transactions.deposits.class, Deposit::ActiveRecord_Relation
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment