Created
July 31, 2014 17:35
-
-
Save zoltankiss/20f6b2130c533528001c to your computer and use it in GitHub Desktop.
test nested has many through association with unpersisted parent instance which is then saved
This file contains hidden or 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
| unless File.exist?('Gemfile') | |
| File.write('Gemfile', <<-GEMFILE) | |
| source 'https://rubygems.org' | |
| gem 'rails', github: 'rails/rails' | |
| gem 'arel', github: 'rails/arel' | |
| gem 'rack', github: 'rack/rack' | |
| gem 'i18n', github: 'svenfuchs/i18n' | |
| gem 'sqlite3' | |
| GEMFILE | |
| system 'bundle' | |
| end | |
| require 'bundler' | |
| Bundler.setup(:default) | |
| 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 :posts do |t| | |
| t.integer :author_id | |
| end | |
| create_table :authors do |t| | |
| end | |
| create_table :books do |t| | |
| t.integer :author_id | |
| end | |
| create_table :subscriptions do |t| | |
| t.integer :book_id | |
| end | |
| end | |
| class Post < ActiveRecord::Base | |
| belongs_to :author | |
| end | |
| class Author < ActiveRecord::Base | |
| has_one :post | |
| has_many :books | |
| has_many :subscriptions, through: :books | |
| end | |
| class Book < ActiveRecord::Base | |
| belongs_to :author | |
| has_many :subscriptions | |
| end | |
| class Subscription < ActiveRecord::Base | |
| belongs_to :book | |
| end | |
| class HasManyThroughAssociationWithUnpersistedParentInstance < Minitest::Test | |
| def test_nested_has_many_through_association_with_unpersisted_parent_instance_then_saved | |
| post_with_nested_has_many_through = Class.new(Post) do | |
| def self.name; 'PostWithNestedHasManyThrough'; end | |
| has_many :books, through: :author | |
| has_many :subscriptions, through: :books | |
| end | |
| post = post_with_nested_has_many_through.new | |
| post.author = Author.create! | |
| book = Book.create! | |
| post.author.books << book | |
| subscription = Subscription.create! | |
| book.subscriptions << subscription | |
| assert_equal [subscription], post.subscriptions.to_a | |
| post.save | |
| assert_equal [subscription], post.subscriptions.to_a | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment