Last active
August 29, 2015 14:23
-
-
Save jordanthomas/e6cc3f7c2db773adeb7d to your computer and use it in GitHub Desktop.
Association is nil when model accepts_nested_attributes
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
begin | |
require 'bundler/inline' | |
rescue LoadError => e | |
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' | |
raise e | |
end | |
gemfile(true) do | |
source 'https://rubygems.org' | |
# Activate the gem you are reporting the issue against. | |
gem 'activerecord', '4.2.2' | |
gem 'sqlite3' | |
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 :cars do |t| | |
end | |
create_table :doors do |t| | |
t.references :car | |
end | |
create_table :wheels do |t| | |
t.references :car | |
end | |
create_table :seats do |t| | |
t.references :car | |
end | |
end | |
class Car < ActiveRecord::Base | |
has_many :doors | |
has_many :wheels | |
accepts_nested_attributes_for :wheels | |
has_many :seats, inverse_of: :car | |
accepts_nested_attributes_for :seats | |
end | |
class Door < ActiveRecord::Base | |
belongs_to :car | |
end | |
class Wheel < ActiveRecord::Base | |
belongs_to :car | |
end | |
class Seat < ActiveRecord::Base | |
belongs_to :car, inverse_of: :seats | |
end | |
class CarTest < Minitest::Test | |
def test_assoc_without_nested_attribs | |
c = Car.new | |
d = c.doors.build | |
assert_equal c, d.car | |
end | |
def test_assoc_with_nested_attribs | |
c = Car.new | |
w = c.wheels.build | |
assert_equal c, w.car | |
end | |
def test_assoc_with_nested_attribs_and_inverse_of | |
c = Car.new | |
s = c.seats.build | |
assert_equal c, s.car | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment