Skip to content

Instantly share code, notes, and snippets.

@pacoguzman
Created January 18, 2014 07:18
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 pacoguzman/8487347 to your computer and use it in GitHub Desktop.
Save pacoguzman/8487347 to your computer and use it in GitHub Desktop.
Associations Stuff
unless ENV['AR_VERSION']
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
require 'bundler'
Bundler.setup(:default)
else
# Activate the gem you are reporting the issue against.
gem 'activerecord', ENV['AR_VERSION']
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# 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 :accounts do |t|
end
create_table :images do |t|
t.integer :account_id
end
create_table :platforms do |t|
t.integer :account_id
end
create_table :target_platforms do |t|
t.integer :image_id
t.integer :platform_id
end
end
class Account < ActiveRecord::Base
end
class Image < ActiveRecord::Base
belongs_to :account
has_many :target_platforms
has_many :platforms, :through => :target_platforms
end
class Platform < ActiveRecord::Base
belongs_to :account
end
class TargetPlatform < ActiveRecord::Base
belongs_to :image
belongs_to :platform
before_validation :infer_account
private
def infer_account
@account = image.account
end
end
class BugTest < Minitest::Test
def test_association_stuff
account = Account.create
platform = Platform.create(:account => account)
image = Image.create(:account => account, :platform_ids => [platform.id])
assert_equal 1, TargetPlatform.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment